Transform struct

Transform represents a 2D position for a node.

Fields:

  • X (float64)
  • Y (float64)

Component interface

Component defines behavior that can update each frame.

Methods:

Update


Parameters:
  • *Node
  • Ticker

Entity interface

Entity groups a set of components.

Methods:

Components


Returns:
  • []Component

Node struct

Node is a scene graph node with a transform and children.

Fields:

  • Transform (Transform)
  • Children ([]*Node)
  • Entities ([]Entity)

Methods:

AddChild

AddChild appends a child node.


Parameters:
  • child *Node

Show/Hide Method Body
{
	n.Children = append(n.Children, child)
}

AddEntity

AddEntity attaches an entity to the node.


Parameters:
  • e Entity

References:


Show/Hide Method Body
{
	n.Entities = append(n.Entities, e)
}

NewNode function

NewNode creates an empty node.

Returns:

  • *Node
Show/Hide Function Body
{
	return &Node{}
}

Traverse function

Traverse walks the scene graph depth-first, invoking fn for each node.

Parameters:

  • n *Node
  • fn func(*Node)
Show/Hide Function Body
{
	if n == nil {
		return
	}
	fn(n)
	for _, c := range n.Children {
		Traverse(c, fn)
	}
}

Update function

Update traverses the graph and updates all components on every node.

Parameters:

  • root *Node
  • t Ticker

References:

Show/Hide Function Body
{
	Traverse(root, func(n *Node) {
		for _, e := range n.Entities {
			for _, c := range e.Components() {
				c.Update(n, t)
			}
		}
	})
}

Ticker struct

Ticker mirrors the game loop ticker with delta time and FPS.

Fields:

  • Delta (time.Duration)
  • FPS (float64)

testComponent struct

Fields:

  • count (int)

Methods:

Update


Parameters:
  • _ *Node
  • _ Ticker

References:


Show/Hide Method Body
{ c.count++ }

testEntity struct

Fields:

  • comps ([]Component)

Implements:

  • Entity from scene

Methods:

Components


Returns:
  • []Component

Show/Hide Method Body
{ return e.comps }

TestTraverse function

Parameters:

  • t *testing.T
Show/Hide Function Body
{
	root := NewNode()
	root.AddChild(NewNode())
	root.AddChild(NewNode())

	visited := 0
	Traverse(root, func(*Node) { visited++ })
	if visited != 3 {
		t.Fatalf("expected 3 nodes visited, got %d", visited)
	}
}

TestUpdate function

Parameters:

  • t *testing.T
Show/Hide Function Body
{
	root := NewNode()
	child := NewNode()
	root.AddChild(child)

	c1 := &testComponent{}
	c2 := &testComponent{}
	root.AddEntity(&testEntity{comps: []Component{c1}})
	child.AddEntity(&testEntity{comps: []Component{c2}})

	Update(root, Ticker{})

	if c1.count != 1 {
		t.Fatalf("expected root component updated once, got %d", c1.count)
	}
	if c2.count != 1 {
		t.Fatalf("expected child component updated once, got %d", c2.count)
	}
}

time import

Import example:

import "time"

testing import

Import example:

import "testing"