jl-ecs/examples/rtss-event/main.go
walker e83feb89dd 修改事件封装
修改世界状态更新事件处理方式
2023-12-25 10:57:54 +08:00

102 lines
2.2 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"context"
"fmt"
"time"
"joylink.club/ecs"
)
type FireSwitchDcEvent struct {
Dc bool
}
var fireSwitchDcEventType = ecs.NewEventType[FireSwitchDcEvent]()
type SwitchSystem struct {
count int
}
func (me *SwitchSystem) WhenFireSwitchDcEvent(w ecs.World, event FireSwitchDcEvent) {
fmt.Println("====>>>world-", w.Id(), " SwitchSystem 处理事件 ", event)
}
func (me *SwitchSystem) Update(w ecs.World) {
me.count += 1
fmt.Println("time: ", time.Now().Format(time.StampMilli), "====>>>world-", w.Id(), " SwitchSystem update , count: ", me.count)
fireSwitchDcEventType.Publish(w, &FireSwitchDcEvent{Dc: true})
}
// var switchSystem = &SwitchSystem{}
func NewSwitchSystem() *SwitchSystem {
return &SwitchSystem{
0,
}
}
var (
wd1 = ecs.NewWorld(20)
wd2 = ecs.NewWorld(20)
)
// ////////////////////////////////////////
func main() {
go world1()
go world2()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
for {
select {
case <-ctx.Done():
return
default:
}
fireSwitchDcEventType.Publish(wd2, &FireSwitchDcEvent{Dc: false})
time.Sleep(10 * time.Millisecond)
}
}()
time.Sleep(2 * time.Second)
wd1.Close()
wd2.Close()
time.Sleep(5 * time.Second)
}
func world1() {
world := wd1
world.StartUp()
//
switchSystem := NewSwitchSystem()
world.AddSystem(switchSystem)
ecs.WorldStateChangeEvent.Subscribe(wd1, func(w ecs.World, event ecs.WorldStateChange) {
fmt.Println("世界1状态变更", event)
})
//
fireSwitchDcEventType.Subscribe(world, switchSystem.WhenFireSwitchDcEvent)
//
time.Sleep(3 * time.Second)
//
fireSwitchDcEventType.Publish(world, &FireSwitchDcEvent{Dc: false})
time.Sleep(10 * time.Second)
}
func world2() {
world := wd2
world.StartUp()
//
switchSystem := NewSwitchSystem()
world.AddSystem(switchSystem)
fireSwitchDcEventType.Subscribe(world, switchSystem.WhenFireSwitchDcEvent)
ecs.WorldStateChangeEvent.Subscribe(wd2, func(w ecs.World, event ecs.WorldStateChange) {
fmt.Println("世界2状态变更", event)
})
//
time.Sleep(3 * time.Second)
//
fireSwitchDcEventType.Publish(world, &FireSwitchDcEvent{Dc: false})
time.Sleep(10 * time.Second)
}