call it "scene"

This commit is contained in:
Josh Deprez 2021-07-30 14:25:32 +10:00 committed by Josh Deprez
parent 24d47ba639
commit 14407fe47d
3 changed files with 15 additions and 14 deletions

View file

@ -6,12 +6,12 @@ import "github.com/hajimehoshi/ebiten/v2"
type Game struct {
ScreenWidth int
ScreenHeight int
Layers *Layers
Scene *Scene
}
// Draw draws the entire thing.
func (g *Game) Draw(screen *ebiten.Image) {
g.Layers.Draw(screen, ebiten.GeoM{})
g.Scene.Draw(screen, ebiten.GeoM{})
}
// Layout returns the configured screen width/height.
@ -21,5 +21,5 @@ func (g *Game) Layout(outsideWidth, outsideHeight int) (w, h int) {
// Update just passes the call onto Layers.
func (g *Game) Update() error {
return g.Layers.Update()
return g.Scene.Update()
}

View file

@ -21,14 +21,14 @@ type ZPositioner interface {
Z() float64
}
// Layers
type Layers struct {
// Scene manages drawing and updating a bunch of components.
type Scene struct {
Components []interface{}
needsSort bool
}
// Draw draws all layers in order.
func (l *Layers) Draw(screen *ebiten.Image, geom ebiten.GeoM) {
// Draw draws all components in order.
func (l *Scene) Draw(screen *ebiten.Image, geom ebiten.GeoM) {
for _, i := range l.Components {
if d, ok := i.(Drawer); ok {
d.Draw(screen, geom)
@ -37,13 +37,15 @@ func (l *Layers) Draw(screen *ebiten.Image, geom ebiten.GeoM) {
}
// SetNeedsSort informs l that its layers may be out of order.
func (l *Layers) SetNeedsSort() {
func (l *Scene) SetNeedsSort() {
l.needsSort = true
}
// sortByZ sorts the components by Z position.
// Stable sort is used to avoid z-fighting among layers without a Z.
func (l *Layers) sortByZ() {
// Stable sort is used to avoid Z-fighting among layers without a Z, or
// among those with equal Z. All non-ZPositioners are sorted first.
func (l *Scene) sortByZ() {
l.needsSort = false
sort.SliceStable(l.Components, func(i, j int) bool {
a, aok := l.Components[i].(ZPositioner)
b, bok := l.Components[j].(ZPositioner)
@ -52,11 +54,10 @@ func (l *Layers) sortByZ() {
}
return !aok && bok
})
l.needsSort = false
}
// Update calls Update on all Updater components.
func (l *Layers) Update() error {
func (l *Scene) Update() error {
for _, c := range l.Components {
if u, ok := c.(Updater); ok {
if err := u.Update(); err != nil {

View file

@ -84,11 +84,11 @@ func main() {
game := &engine.Game{
ScreenHeight: screenHeight,
ScreenWidth: screenWidth,
Layers: &engine.Layers{
Scene: &engine.Scene{
Components: components,
},
}
game.Layers.SetNeedsSort()
game.Scene.SetNeedsSort()
if err := ebiten.RunGame(game); err != nil {
log.Fatalf("Game error: %v", err)