ichigo/engine/tiles.go

76 lines
1.5 KiB
Go
Raw Normal View History

2021-07-23 17:05:05 +10:00
package engine
2021-07-23 17:17:56 +10:00
import (
"image"
"github.com/hajimehoshi/ebiten/v2"
)
2021-07-23 17:05:05 +10:00
type Tilemap struct {
2021-07-29 15:09:00 +10:00
Map [][]Tile
2021-07-26 21:19:12 +10:00
Src *ebiten.Image // must be a horizontal tile set
2021-07-23 17:05:05 +10:00
TileSize int
ZPos
}
2021-07-29 17:07:38 +10:00
func (t *Tilemap) Draw(screen *ebiten.Image, geom ebiten.GeoM) {
2021-07-23 17:17:56 +10:00
for j, row := range t.Map {
for i, tile := range row {
var op ebiten.DrawImageOptions
op.GeoM.Translate(float64(i*t.TileSize), float64(j*t.TileSize))
2021-07-29 17:07:38 +10:00
op.GeoM.Concat(geom)
2021-07-23 17:05:05 +10:00
2021-07-29 15:09:00 +10:00
sx := tile.TileIndex() * t.TileSize
2021-07-23 17:17:56 +10:00
src := t.Src.SubImage(image.Rect(sx, 0, sx+t.TileSize, t.TileSize)).(*ebiten.Image)
screen.DrawImage(src, &op)
}
}
2021-07-23 17:05:05 +10:00
}
2021-07-29 15:09:00 +10:00
func (t *Tilemap) Update() error {
for j := range t.Map {
for i := range t.Map[j] {
if tile, ok := t.Map[j][i].(Updater); ok {
if err := tile.Update(); err != nil {
return err
}
}
}
}
return nil
}
type Tile interface {
TileIndex() int
}
type StaticTile int
func (s StaticTile) TileIndex() int { return int(s) }
type AnimatedTile struct {
2021-07-29 15:29:26 +10:00
Frame int // index into AnimDef
DurationTicks int // time spent showing current frame
2021-07-29 15:09:00 +10:00
AnimDef []TileAnimFrameDef
}
func (a *AnimatedTile) TileIndex() int { return a.AnimDef[a.Frame].Tile }
func (a *AnimatedTile) Update() error {
a.DurationTicks++
if a.DurationTicks >= a.AnimDef[a.Frame].DurationTicks {
a.DurationTicks = 0
a.Frame++
}
if a.Frame >= len(a.AnimDef) {
a.Frame = 0
}
return nil
}
type TileAnimFrameDef struct {
Tile int // show this tile
DurationTicks int // show it for this long
}