2018-01-24 05:56:48 -07:00

87 lines
2.0 KiB
Go

package gameobjects
import (
"github.com/faiface/pixel"
"github.com/faiface/pixel/pixelgl"
//"fmt"
)
type Player struct {
PlayerVec pixel.Vec
sprFrame int
spriteSheet pixel.Picture
sprFrames []pixel.Rect
sprite *pixel.Sprite
speed float64
dir int
animation Animate
}
func NewPlayer(win *pixelgl.Window, spriteSheet pixel.Picture) Player {
var p Player
p.PlayerVec = pixel.Vec{
X: win.Bounds().Max.X / 2,
Y: win.Bounds().Max.Y / 2,
}
p.sprFrame = 9
p.spriteSheet = spriteSheet
p.sprFrames = createSpriteFrames(spriteSheet)
p.animation = NewAnimation(p.spriteSheet, p.sprFrames)
//p.sprite = pixel.NewSprite(spriteSheet, p.sprFrames[p.sprFrame])
p.speed = 10.0
return p
}
func (p *Player) Update(win *pixelgl.Window, dt int64) {
var vecX, vecY float64 = 0, 0
speed := p.speed
if win.Pressed(pixelgl.KeyA) { //left
p.sprFrame = 6
p.dir = 2
vecX -= speed
}
if win.Pressed(pixelgl.KeyD) { //Right
p.sprFrame = 3
p.dir = 3
vecX += speed
}
if win.Pressed(pixelgl.KeyS) { //Down
p.sprFrame = 9
p.dir = 1
vecY -= speed
}
if win.Pressed(pixelgl.KeyW) { //up
p.sprFrame = 0
p.dir = 0
vecY += speed
}
if vecY == 0 && vecX == 0 {
p.animation.Idle = true
} else {
p.animation.Idle = false
}
//p.sprite.Set(p.spriteSheet, p.sprFrames[p.sprFrame])
p.animation.Dir = p.dir
p.animation.Update(dt)
p.PlayerVec.X += vecX
p.PlayerVec.Y += vecY
}
func (p *Player) Render(win *pixelgl.Window) { //include batch later
//p.sprite.Draw(win, pixel.IM.Scaled(pixel.ZV, 4).Moved(p.PlayerVec))
p.animation.Render(win, p.PlayerVec)
}
func createSpriteFrames(spriteSheet pixel.Picture) []pixel.Rect {
var sprFrames []pixel.Rect
var frameHeight, frameWidth float64 = 96, 96
for y := spriteSheet.Bounds().Min.Y; y < frameHeight*4; y += 96 {
for x := spriteSheet.Bounds().Min.X; x < frameWidth*3; x += 96 {
sprFrames = append(sprFrames, pixel.R(x, y, x+96, y+96)) // (x, y, width, height) of frame
}
}
return sprFrames
}