openquell/systems/animation_system.go

89 lines
1.9 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 (
"log/slog"
"openquell/components"
2024-02-09 20:20:13 +01:00
. "openquell/components"
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.Filter2[Position, Renderable]
2024-02-09 20:20:13 +01:00
Cellsize int
}
func NewAnimationSystem(world *ecs.World, cellsize int) System {
system := &AnimationSystem{
Selector: generic.NewFilter2[Position, Renderable](),
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 {
EntitiesToRemove := []ecs.Entity{}
2024-02-09 20:20:13 +01:00
query := system.Selector.Query(system.World)
for query.Next() {
_, render := query.Get()
for animationtype, animate := range render.Animations() {
if animate.Active {
if animate.Timer.IsReady() {
switch {
// animation shows from earlier tick, animate
case animate.Index > -1 && animate.Index < len(animate.Sprites)-1:
animate.Index += 1
animate.Timer.Start(animate.GetDuration())
default:
// last sprite reached
if animate.Loop {
animate.Index = 0
animate.Timer.Start(animate.GetDuration())
}
if animationtype == components.Destruction {
EntitiesToRemove = append(EntitiesToRemove, query.Entity())
}
}
} else {
animate.Timer.Update()
}
}
2024-02-09 20:20:13 +01:00
}
}
for _, entity := range EntitiesToRemove {
slog.Debug("remove collectible")
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, render := query.Get()
2024-02-10 19:45:06 +01:00
for _, animate := range render.Animations() {
if animate.Active {
op.GeoM.Reset()
op.GeoM.Translate(float64(pos.X), float64(pos.Y))
sprite := animate.GetSprite()
screen.DrawImage(sprite, op)
}
}
2024-02-10 19:45:06 +01:00
}
}