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.
56 lines
1.3 KiB
56 lines
1.3 KiB
package gohan |
|
|
|
import ( |
|
"sync" |
|
) |
|
|
|
var componentMutex sync.Mutex |
|
|
|
// ComponentID is a component identifier. Each Component is assigned a unique ID |
|
// via NewComponentID, and implements a ComponentID method returning its ID. |
|
type ComponentID int |
|
|
|
// Component represents data for an entity, and how it interacts with the world. |
|
type Component interface { |
|
ComponentID() ComponentID |
|
} |
|
|
|
// NewComponentID returns the next available ComponentID. |
|
func (w *World) NewComponentID() ComponentID { |
|
entityMutex.Lock() |
|
defer entityMutex.Unlock() |
|
|
|
componentMutex.Lock() |
|
defer componentMutex.Unlock() |
|
|
|
w.maxComponentID++ |
|
|
|
for i := Entity(1); i <= w.maxEntityID; i++ { |
|
w.components[i] = append(w.components[i], nil) |
|
} |
|
|
|
return w.maxComponentID |
|
} |
|
|
|
// AddComponent adds a Component to an Entity. |
|
func (w *World) AddComponent(entity Entity, component Component) { |
|
componentMutex.Lock() |
|
defer componentMutex.Unlock() |
|
|
|
componentID := component.ComponentID() |
|
|
|
w.components[entity][componentID] = component |
|
|
|
entityMutex.Lock() |
|
defer entityMutex.Unlock() |
|
w.modifiedEntities = append(w.modifiedEntities, entity) |
|
} |
|
|
|
// Component gets a Component of an Entity. |
|
func (w *World) Component(entity Entity, componentID ComponentID) interface{} { |
|
components := w.components[entity] |
|
if components == nil { |
|
return nil |
|
} |
|
return components[componentID] |
|
}
|
|
|