ichigo/engine/tiles.go

78 lines
1.6 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 (
2021-07-30 17:26:23 +10:00
"encoding/gob"
2021-07-23 17:17:56 +10:00
"image"
"github.com/hajimehoshi/ebiten/v2"
)
2021-07-23 17:05:05 +10:00
2021-07-30 17:26:23 +10:00
func init() {
gob.Register(AnimatedTile{})
gob.Register(StaticTile(0))
gob.Register(Tilemap{})
}
2021-07-31 19:49:24 +10:00
// Tilemap renders a grid of tiles.
2021-07-23 17:05:05 +10:00
type Tilemap struct {
2021-08-01 17:08:26 +10:00
Hidden bool
ID
2021-07-30 15:18:36 +10:00
Map [][]Tile
2021-07-31 16:38:54 +10:00
Src ImageRef // must be a horizontal tile set
2021-07-30 15:18:36 +10:00
TileSize int
2021-08-01 20:28:33 +10:00
Transform GeoMDef
2021-07-23 17:05:05 +10:00
ZPos
}
2021-07-31 19:49:24 +10:00
// Draw draws the tilemap.
2021-07-29 17:07:38 +10:00
func (t *Tilemap) Draw(screen *ebiten.Image, geom ebiten.GeoM) {
2021-08-01 17:08:26 +10:00
if t.Hidden {
return
}
2021-08-01 20:28:33 +10:00
geom.Concat(*t.Transform.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-31 20:06:49 +10:00
src := t.Src.Image().SubImage(image.Rect(sx, 0, sx+t.TileSize, t.TileSize)).(*ebiten.Image)
2021-07-23 17:17:56 +10:00
screen.DrawImage(src, &op)
}
}
2021-07-23 17:05:05 +10:00
}
2021-07-29 15:09:00 +10:00
2021-07-31 19:49:24 +10:00
// Update calls Update on any tiles that are Updaters, e.g. AnimatedTile.
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
}
2021-07-31 19:49:24 +10:00
// Tile is the interface needed by Tilemap.
2021-07-29 15:09:00 +10:00
type Tile interface {
TileIndex() int
}
2021-07-31 19:49:24 +10:00
// StaticTile returns a fixed tile index.
2021-07-29 15:09:00 +10:00
type StaticTile int
func (s StaticTile) TileIndex() int { return int(s) }
2021-07-31 19:49:24 +10:00
// AnimatedTile uses an Anim to choose a tile index.
2021-07-29 15:09:00 +10:00
type AnimatedTile struct {
2021-07-31 20:06:49 +10:00
AnimRef
2021-07-29 15:09:00 +10:00
}
2021-07-31 20:06:49 +10:00
func (a *AnimatedTile) TileIndex() int { return a.Anim().CurrentFrame() }
func (a *AnimatedTile) Update() error { return a.Anim().Update() }