You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
67 lines
1.7 KiB
67 lines
1.7 KiB
package gohan |
|
|
|
import "fmt" |
|
|
|
// ComponentID is a component identifier. Each Component is assigned a unique ID |
|
// via NextComponentID, and implements a ComponentID method which returns the ID. |
|
type ComponentID int |
|
|
|
// Component represents data for an entity, and how it interacts with the world. |
|
type Component interface { |
|
ComponentID() ComponentID |
|
} |
|
|
|
var nextComponentID ComponentID |
|
|
|
// NextComponentID returns the next available ComponentID. |
|
func NextComponentID() ComponentID { |
|
id := nextComponentID |
|
nextComponentID++ |
|
return id |
|
} |
|
|
|
func (entity EntityID) propagateChanges() { |
|
for i, system := range gameSystems { |
|
systemEntityIndex := -1 |
|
for j, systemEntity := range gameSystemEntities[i] { |
|
if systemEntity == entity { |
|
systemEntityIndex = j |
|
break |
|
} |
|
} |
|
|
|
if system.Matches(entity) { |
|
if systemEntityIndex != -1 { |
|
// Already attached. |
|
continue |
|
} |
|
|
|
gameSystemEntities[i] = append(gameSystemEntities[i], entity) |
|
print(fmt.Sprintf("Attached entity %d to system %d.", entity, i)) |
|
} else if systemEntityIndex != -1 { |
|
// Detach from system. |
|
gameSystemEntities[i] = append(gameSystemEntities[i][:systemEntityIndex], gameSystemEntities[i][systemEntityIndex+1:]...) |
|
} |
|
} |
|
} |
|
|
|
// AddComponent adds a Component to an Entity. |
|
func (entity EntityID) AddComponent(component Component) { |
|
componentID := component.ComponentID() |
|
|
|
if gameComponents[entity] == nil { |
|
gameComponents[entity] = make(map[ComponentID]interface{}) |
|
} |
|
gameComponents[entity][componentID] = component |
|
|
|
entity.propagateChanges() |
|
} |
|
|
|
// Component gets a Component of an Entity. |
|
func (entity EntityID) Component(componentID ComponentID) interface{} { |
|
components := gameComponents[entity] |
|
if components == nil { |
|
return nil |
|
} |
|
return components[componentID] |
|
}
|
|
|