Files
old-9heroja/hero/hero.go
2023-11-21 20:12:56 +01:00

125 lines
2.2 KiB
Go

package hero
import (
"bytes"
"github.com/hajimehoshi/ebiten/v2"
"gitlab.com/kbr4/9heroja/configuration"
"gitlab.com/kbr4/9heroja/resources"
"image"
"log"
"time"
)
const WalkSpeedMs = 300
var (
heroImage *ebiten.Image
walkTicker *time.Ticker
)
type Hero struct {
step int
direction configuration.Direction
}
type spritePosition struct {
x int
y int
}
func (h *Hero) DrawHero(screen *ebiten.Image) {
// set movement positions to be hashmap of sprite positions for each direction
movementPositions := map[configuration.Direction][]spritePosition{}
movementPositions[configuration.North] = []spritePosition{
{0, 166},
{33, 166},
{66, 166},
{99, 166},
{132, 166},
{99, 166},
{66, 166},
{33, 166},
}
movementPositions[configuration.NorthEast] = []spritePosition{
{168, 0},
{201, 0},
{0, 33},
{33, 33},
{66, 33},
{33, 33},
{0, 33},
{201, 0},
}
movementPositions[configuration.South] = []spritePosition{
{66, 132},
{0, 99},
{33, 99},
{66, 99},
{99, 99},
{66, 99},
{33, 99},
{0, 99},
}
p := movementPositions[h.direction][h.step%8]
op := &ebiten.DrawImageOptions{}
screenWidth := screen.Bounds().Max.X
screenHeight := screen.Bounds().Max.Y
// ground
op.GeoM.Reset()
op.GeoM.Translate(float64(screenWidth/2-16), float64(screenHeight/2-16))
//op.GeoM.Translate(float64(i*tileSize-floorMod(g.cameraX, tileSize)),
// float64((ny-1)*tileSize-floorMod(g.cameraY, tileSize)))
screen.DrawImage(heroImage.SubImage(image.Rect(p.x+1, p.y, p.x+resources.HeroTileSize, p.y+resources.HeroTileSize)).(*ebiten.Image), op)
}
func init() {
img, _, err := image.Decode(bytes.NewReader(resources.Hero_png))
if err != nil {
log.Fatal(err)
}
heroImage = ebiten.NewImageFromImage(img)
walkTicker = time.NewTicker(WalkSpeedMs * time.Millisecond)
// go routine that runs on every tick and increases step
}
func NewHero() *Hero {
hero := &Hero{
step: 0,
}
go func() {
for {
select {
case <-walkTicker.C:
hero.step++
if hero.step > 7 {
hero.step = 0
}
}
}
}()
return hero
}
func (h *Hero) Walk() {
walkTicker.Reset(WalkSpeedMs * time.Millisecond)
}
func (h *Hero) ChangeDirection(d configuration.Direction) {
h.direction = d
}
func (h *Hero) Stop() {
h.step = 2
walkTicker.Stop()
}