rts-sim-module/system/timer_system.go

76 lines
1.5 KiB
Go
Raw Normal View History

2023-08-15 16:50:24 +08:00
package system
import (
"time"
"github.com/yohamta/donburi/filter"
"joylink.club/ecs"
)
2023-09-12 17:07:17 +08:00
var SystemTimerComponent = ecs.NewComponentType[SystemTimer]()
var timerQuery *ecs.Query = ecs.NewQuery(filter.Contains(SystemTimerComponent))
2023-08-15 16:50:24 +08:00
2023-09-15 13:48:48 +08:00
// TimerSystem 系统时钟操作
2023-08-15 16:50:24 +08:00
type TimerSystem struct {
}
func NewTimerSystem() *TimerSystem {
return &TimerSystem{}
}
2023-09-15 13:48:48 +08:00
// Update world 执行
2023-08-15 16:50:24 +08:00
func (me *TimerSystem) Update(w ecs.World) {
if e, ok := timerQuery.First(w); ok {
2023-09-12 17:07:17 +08:00
timer := SystemTimerComponent.Get(e)
2023-08-15 16:50:24 +08:00
timer.Tick(w.Tick())
}
}
2023-09-15 13:48:48 +08:00
// ResetWorldTimer 重置world时间
2023-08-15 16:50:24 +08:00
func ResetWorldTimer(w ecs.World, time time.Time) {
if e, ok := timerQuery.First(w); ok {
2023-09-12 17:07:17 +08:00
timer := SystemTimerComponent.Get(e)
2023-08-15 16:50:24 +08:00
timer.ResetTime(time)
}
}
2023-09-15 13:48:48 +08:00
// GetWorldNow 获取world当前时间
2023-08-15 16:50:24 +08:00
func GetWorldNow(w ecs.World) *time.Time {
if e, ok := timerQuery.First(w); ok {
2023-09-12 17:07:17 +08:00
timer := SystemTimerComponent.Get(e)
2023-08-15 16:50:24 +08:00
now := timer.Now()
return &now
}
return nil
}
2023-09-12 17:07:17 +08:00
/////////////////////////////////////////////////////////////////
2023-09-15 13:48:48 +08:00
// SystemTimer 系统时钟,单例
2023-09-12 17:07:17 +08:00
type SystemTimer struct {
timer *time.Time
}
2023-09-15 13:48:48 +08:00
// NewSystemTimer 以指定时间构建
2023-09-12 17:07:17 +08:00
func NewSystemTimer(time *time.Time) *SystemTimer {
return &SystemTimer{
timer: time,
}
}
2023-09-15 13:48:48 +08:00
// ResetTime 重置时间
2023-09-12 17:07:17 +08:00
func (me *SystemTimer) ResetTime(time time.Time) {
*me.timer = time
}
2023-09-15 13:48:48 +08:00
// Now 获取当前时间的副本
2023-09-12 17:07:17 +08:00
func (me *SystemTimer) Now() time.Time {
return *me.timer
}
2023-09-15 13:48:48 +08:00
// Tick tick系统时钟,单位ms
2023-09-12 17:07:17 +08:00
func (me *SystemTimer) Tick(tick int) {
*me.timer = me.timer.Add(time.Duration(tick) * time.Millisecond)
}