openquell/systems/animation_system.go

78 lines
1.7 KiB
Go
Raw Normal View History

2024-02-10 19:45:06 +01:00
package systems
2024-02-09 20:20:13 +01:00
import (
. "openquell/components"
"openquell/config"
2024-02-09 20:20:13 +01:00
2024-02-10 19:45:06 +01:00
"github.com/hajimehoshi/ebiten/v2"
2024-02-09 20:20:13 +01:00
"github.com/mlange-42/arche/ecs"
"github.com/mlange-42/arche/generic"
)
type AnimationSystem struct {
2024-02-09 20:20:13 +01:00
World *ecs.World
Selector *generic.Filter3[Position, Animation, Timer]
2024-02-09 20:20:13 +01:00
Cellsize int
}
func NewAnimationSystem(world *ecs.World, cellsize int) System {
system := &AnimationSystem{
Selector: generic.NewFilter3[Position, Animation, Timer](),
2024-02-10 19:45:06 +01:00
World: world,
Cellsize: cellsize,
2024-02-09 20:20:13 +01:00
}
return system
}
func (system *AnimationSystem) Update() error {
2024-02-09 20:20:13 +01:00
// display debris after collecting
EntitiesToRemove := []ecs.Entity{}
2024-02-09 20:20:13 +01:00
query := system.Selector.Query(system.World)
for query.Next() {
// we loop, but it's only one anyway
_, animation, timer := query.Get()
2024-02-09 20:20:13 +01:00
animation.Show = true
if timer.IsReady() {
switch {
// animation shows from earlier tick, animate
case animation.Index > -1 && animation.Index < len(animation.Tiles)-1:
animation.Index++
timer.Start(config.ANIMATION_LOOPWAIT)
default:
// last sprite reached, remove it
EntitiesToRemove = append(EntitiesToRemove, query.Entity())
}
} else {
timer.Update()
2024-02-09 20:20:13 +01:00
}
2024-02-09 20:20:13 +01:00
}
for _, entity := range EntitiesToRemove {
system.World.RemoveEntity(entity)
}
return nil
2024-02-09 20:20:13 +01:00
}
2024-02-10 19:45:06 +01:00
func (system *AnimationSystem) Draw(screen *ebiten.Image) {
// write animations (these are no tiles!)
2024-02-10 19:45:06 +01:00
op := &ebiten.DrawImageOptions{}
query := system.Selector.Query(system.World)
for query.Next() {
pos, animation, _ := query.Get()
2024-02-10 19:45:06 +01:00
if animation.Show {
op.GeoM.Reset()
op.GeoM.Translate(float64(pos.X), float64(pos.Y))
screen.DrawImage(animation.Tiles[animation.Index], op)
}
2024-02-10 19:45:06 +01:00
}
}