136 lines
2.5 KiB
Go
136 lines
2.5 KiB
Go
package entity
|
|
|
|
import (
|
|
"log"
|
|
"math"
|
|
|
|
"gitea.wisellama.rocks/Project-Ely/project-ely/internal/vector"
|
|
"github.com/veandco/go-sdl2/sdl"
|
|
)
|
|
|
|
type penguin struct {
|
|
// 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{}
|
|
|
|
p := penguin{
|
|
currentAnimation: penguinAnimations[PENGUIN_DEFAULT],
|
|
animationStep: 0,
|
|
facingRight: true,
|
|
|
|
worldPosition: &position,
|
|
speed: 2.0,
|
|
direction: &direction,
|
|
}
|
|
|
|
return &p
|
|
}
|
|
|
|
func (p *penguin) Draw() error {
|
|
step := p.animationStep / p.currentAnimation.speed
|
|
|
|
//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(name string) {
|
|
a, exists := penguinAnimations[name]
|
|
|
|
if !exists {
|
|
log.Printf("animation does not exist: %v", name)
|
|
a = penguinAnimations[PENGUIN_DEFAULT]
|
|
}
|
|
|
|
if a != p.currentAnimation {
|
|
p.animationStep = 0
|
|
}
|
|
|
|
p.currentAnimation = a
|
|
}
|
|
|
|
func (p *penguin) MoveX(x float64) {
|
|
p.direction.X = x
|
|
p.updateAnimation = true
|
|
}
|
|
|
|
func (p *penguin) MoveY(y float64) {
|
|
// (0,0) is the top left, so negative y moves up
|
|
p.direction.Y = y
|
|
p.updateAnimation = true
|
|
}
|
|
|
|
func (p *penguin) SetMoveAnimation() {
|
|
x := p.direction.X
|
|
y := p.direction.Y
|
|
|
|
if x == 0 && y == 0 {
|
|
// Stationary
|
|
if p.facingRight {
|
|
p.SetAnimation(PENGUIN_STATIONARY_RIGHT)
|
|
} else {
|
|
p.SetAnimation(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(PENGUIN_WALK_RIGHT)
|
|
} else {
|
|
p.SetAnimation(PENGUIN_WALK_LEFT)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (p *penguin) Update() error {
|
|
if p.updateAnimation {
|
|
p.SetMoveAnimation()
|
|
p.updateAnimation = false
|
|
}
|
|
|
|
p.direction.Normalize()
|
|
x := p.direction.X * p.speed
|
|
y := p.direction.Y * p.speed
|
|
|
|
log.Printf("X: %v, Y: %v\n", x, y)
|
|
p.worldPosition.X += x
|
|
p.worldPosition.Y += y
|
|
return nil
|
|
}
|