project-ely/internal/game/entity/types/penguin.go

157 lines
2.9 KiB
Go

package types
import (
"log"
"math"
"sync"
"gitea.wisellama.rocks/Project-Ely/project-ely/internal/game/entity/animation"
"gitea.wisellama.rocks/Project-Ely/project-ely/internal/vector"
"github.com/veandco/go-sdl2/sdl"
)
type penguin struct {
mx sync.RWMutex
// Animation parameters
currentAnimation EntityAnimation
animationStep int32
facingRight bool
updateAnimation bool
// Physical parameters
worldPosition *vector.Vec2F
direction *vector.Vec2F
speed float64
}
func NewPenguin(renderer *sdl.Renderer) *penguin {
position := vector.Vec2F{}
direction := vector.Vec2F{}
speed := 1.0
p := penguin{
currentAnimation: animation.PenguinAnimations[animation.PENGUIN_DEFAULT],
animationStep: 0,
facingRight: true,
worldPosition: &position,
speed: speed,
direction: &direction,
}
return &p
}
func (p *penguin) Draw() error {
step := p.animationStep / p.currentAnimation.GetSpeed()
// TODO
//windowPosition := worldPosToWindowPos()
windowPosition := &sdl.Point{
X: int32(math.Round(p.worldPosition.X)),
Y: int32(math.Round(p.worldPosition.Y)),
}
err := p.currentAnimation.Draw(step, windowPosition)
if err != nil {
return err
}
p.animationStep = 1 + p.animationStep
return nil
}
func (p *penguin) SetPosition(vec *vector.Vec2F) {
p.worldPosition = vec
}
func (p *penguin) SetAnimation(id int) {
a, exists := animation.PenguinAnimations[id]
if !exists {
log.Printf("animation does not exist: %v", id)
a = animation.PenguinAnimations[animation.PENGUIN_DEFAULT]
}
if a != p.currentAnimation {
p.animationStep = 0
}
p.currentAnimation = a
}
func (p *penguin) MoveX(x float64) {
p.mx.Lock()
defer p.mx.Unlock()
p.direction.X = x
p.direction.Normalize()
p.updateAnimation = true
}
func (p *penguin) MoveY(y float64) {
p.mx.Lock()
defer p.mx.Unlock()
// (0,0) is the top left, so negative y moves up
p.direction.Y = y
p.direction.Normalize()
p.updateAnimation = true
}
func (p *penguin) SetSpeed(s float64) {
p.speed = s
}
func (p *penguin) GetSpeed() float64 {
return p.speed
}
func (p *penguin) SetMoveAnimation() {
x := p.direction.X
y := p.direction.Y
if x == 0 && y == 0 {
// Stationary
if p.facingRight {
p.SetAnimation(animation.PENGUIN_STATIONARY_RIGHT)
} else {
p.SetAnimation(animation.PENGUIN_STATIONARY_LEFT)
}
} else {
// Moving
// Update which direction we're facing
if x > 0 {
p.facingRight = true
} else if x < 0 {
p.facingRight = false
}
// if x == 0, stay facing whatever direction we were previously facing
if p.facingRight {
p.SetAnimation(animation.PENGUIN_WALK_RIGHT)
} else {
p.SetAnimation(animation.PENGUIN_WALK_LEFT)
}
}
}
func (p *penguin) Update() error {
if p.updateAnimation {
p.SetMoveAnimation()
p.updateAnimation = false
}
x := p.direction.X * p.speed
y := p.direction.Y * p.speed
p.worldPosition.X += x
p.worldPosition.Y += y
return nil
}