Entity Component System framework for Ebitengine
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.

60 lines
1.4 KiB

package gohan
import (
"sync"
"time"
)
// Entity is an entity identifier.
type Entity int
var maxEntityID Entity
var entityMutex sync.Mutex
// NewEntity returns a new (or previously removed and cleared) Entity. Because
// Gohan reuses removed Entity IDs, a previously removed ID may be returned.
func NewEntity() Entity {
entityMutex.Lock()
defer entityMutex.Unlock()
if len(availableEntityIDs) > 0 {
id := availableEntityIDs[0]
availableEntityIDs = availableEntityIDs[1:]
allEntities = append(allEntities, id)
return id
}
maxEntityID++
allEntities = append(allEntities, maxEntityID)
gameComponents = append(gameComponents, make([]interface{}, maxComponentID+1))
return maxEntityID
}
// Remove removes the provided Entity's components, causing it to no longer be
// handled by any system. Because Gohan reuses removed EntityIDs, applications
// must also remove any internal references to the removed Entity.
func (entity Entity) Remove() {
entityMutex.Lock()
defer entityMutex.Unlock()
for i, e := range allEntities {
if e == entity {
allEntities = append(allEntities[:i], allEntities[i+1:]...)
removedEntities = append(removedEntities, e)
return
}
}
}
var numEntities int
var numEntitiesT time.Time
// ActiveEntities returns the number of currently active entities.
func ActiveEntities() int {
if time.Since(numEntitiesT) >= time.Second {
numEntities = len(allEntities)
numEntitiesT = time.Now()
}
return numEntities
}