From b9ab61316778b97c1b810e2e791fb61bf59303d2 Mon Sep 17 00:00:00 2001 From: Josh Deprez Date: Fri, 23 Jul 2021 17:05:05 +1000 Subject: [PATCH] Composable z-position --- engine/debug.go | 7 ++++--- engine/game.go | 9 +++++---- engine/tiles.go | 16 ++++++++++++++++ engine/z.go | 5 +++++ 4 files changed, 30 insertions(+), 7 deletions(-) create mode 100644 engine/tiles.go create mode 100644 engine/z.go diff --git a/engine/debug.go b/engine/debug.go index 198f5a5..42a5af1 100644 --- a/engine/debug.go +++ b/engine/debug.go @@ -2,6 +2,7 @@ package engine import ( "fmt" + "math" "github.com/hajimehoshi/ebiten/v2" "github.com/hajimehoshi/ebiten/v2/ebitenutil" @@ -14,7 +15,7 @@ func (TPSDisplay) Draw(screen *ebiten.Image) { ebitenutil.DebugPrint(screen, fmt.Sprintf("TPS: %0.2f", ebiten.CurrentTPS())) } -func (TPSDisplay) DrawAfter(Drawer) bool { - // Always draw last - return true +func (TPSDisplay) Z() float64 { + // Always draw on top + return math.MaxFloat64 } diff --git a/engine/game.go b/engine/game.go index b697ee3..39c799f 100644 --- a/engine/game.go +++ b/engine/game.go @@ -15,7 +15,7 @@ type Updater interface { // DrawAfter is used to reorder components. type Drawer interface { Draw(*ebiten.Image) - DrawAfter(Drawer) bool + Z() float64 } // Game implements the ebiten methods using a collection of components. @@ -52,13 +52,14 @@ func (g *Game) Layout(outsideWidth, outsideHeight int) (w, h int) { } // Sort sorts the components by draw order. -// Non-Drawers are sorted first. +// Non-Drawers are sorted before all Drawers. func (g *Game) Sort() { - sort.Slice(g.Components, func(i, j int) bool { + // SliceStable to avoid z-fighting (among Non-Drawers and equal Drawers) + sort.SliceStable(g.Components, func(i, j int) bool { a, aok := g.Components[i].(Drawer) b, bok := g.Components[j].(Drawer) if aok && bok { - return b.DrawAfter(a) + return a.Z() < b.Z() } return !aok && bok }) diff --git a/engine/tiles.go b/engine/tiles.go new file mode 100644 index 0000000..2c075eb --- /dev/null +++ b/engine/tiles.go @@ -0,0 +1,16 @@ +package engine + +import "github.com/hajimehoshi/ebiten/v2" + +type Tilemap struct { + Map [][]int + Src *ebiten.Image + TileSize int + GeoM *ebiten.GeoM + + ZPos +} + +func (t *Tilemap) Draw(screen *ebiten.Image) { + +} diff --git a/engine/z.go b/engine/z.go new file mode 100644 index 0000000..7b651b4 --- /dev/null +++ b/engine/z.go @@ -0,0 +1,5 @@ +package engine + +type ZPos float64 + +func (z ZPos) Z() float64 { return float64(z) }