package system import ( "fmt" "github.com/yohamta/donburi/filter" "joylink.club/ecs" ) // PercentageDeviceState 百分比设备 // 起始位置p=0,终点位置p=100000,总路程100000 type PercentageDeviceState struct { //速度,矢量 V int64 //位置,[PD_L,PD_M] P int64 } func NewPercentageDeviceStateL() *PercentageDeviceState { return &PercentageDeviceState{V: 0, P: PD_L} } func NewPercentageDeviceStateM() *PercentageDeviceState { return &PercentageDeviceState{V: 0, P: PD_M} } func (me *PercentageDeviceState) isToL() bool { return me.P <= PD_L } func (me *PercentageDeviceState) isToM() bool { return me.P >= PD_M } // GetRate 获取百分比即(P/(PD_M-PD_L))*100 func (me *PercentageDeviceState) GetRate() int8 { if me.P < PD_L { me.P = PD_L } if me.P > PD_M { me.P = PD_M } return int8((float64(me.P) / float64(PD_M)) * float64(100)) } // SetRate 设置百分比即P=(PD_M-PD_L)*(rate/100) func (me *PercentageDeviceState) SetRate(rate int8) { if rate < 0 || rate > 100 { panic(fmt.Sprintf("rate须在[0,100]中,rate=%d", rate)) } me.P = int64(float64(PD_M-PD_L) * (float64(rate) / float64(100))) } // 百分比设备位置范围 const ( PD_L int64 = 0 PD_M int64 = 100000 ) // PercentageDeviceStateComponent 一维移动的物体组件 var PercentageDeviceStateComponent = ecs.NewComponentType[PercentageDeviceState]() var PercentageDeviceState1Component = ecs.NewComponentType[PercentageDeviceState]() var PercentageDeviceState2Component = ecs.NewComponentType[PercentageDeviceState]() type PercentageMovableSystem struct { query *ecs.Query } func NewPercentageMovableSystem() *PercentageMovableSystem { return &PercentageMovableSystem{ query: ecs.NewQuery(filter.Or(filter.Contains(PercentageDeviceStateComponent), filter.Contains(PercentageDeviceState1Component), filter.Contains(PercentageDeviceState2Component))), } } // Update world 执行 func (me *PercentageMovableSystem) Update(w ecs.World) { me.query.Each(w, func(e *ecs.Entry) { var state *PercentageDeviceState if e.HasComponent(PercentageDeviceStateComponent) { state = PercentageDeviceStateComponent.Get(e) } if e.HasComponent(PercentageDeviceState1Component) { state = PercentageDeviceState1Component.Get(e) } if e.HasComponent(PercentageDeviceState2Component) { state = PercentageDeviceState2Component.Get(e) } if state != nil { me.move(w, state) } }) } func (me *PercentageMovableSystem) move(w ecs.World, state *PercentageDeviceState) { state.P += state.V * int64(w.Tick()) if state.P < PD_L { state.P = PD_L } if state.P > PD_M { state.P = PD_M } }