Add Init,Update,Destroy to Comp+HasComp,DestroyComp funcs

This commit is contained in:
bloeys
2022-12-06 06:07:49 +04:00
parent 84cd8c28c8
commit b025afe1b4
6 changed files with 73 additions and 30 deletions

View File

@ -1,27 +1,37 @@
package entity
import "github.com/bloeys/nmage/assert"
type Comp interface {
// This ensures that implementors of the Comp interface
// always embed BaseComp
base()
Name() string
Init(parent *Entity)
Update()
Destroy()
}
var _ Comp = &BaseComp{}
func AddComp[T Comp](e *Entity, c T) {
type BaseComp struct {
}
assert.T(!HasComp[T](e), "Entity with id %v already has component with name %s", e.ID, c.Name())
func (b *BaseComp) base() {
}
func (b *BaseComp) Name() string {
return "Base Component"
}
func AddComp(e *Entity, c Comp) {
e.Comps = append(e.Comps, c)
c.Init(e)
}
func HasComp[T Comp](e *Entity) bool {
for i := 0; i < len(e.Comps); i++ {
_, ok := e.Comps[i].(T)
if ok {
return true
}
}
return false
}
func GetComp[T Comp](e *Entity) (out T) {
@ -37,16 +47,16 @@ func GetComp[T Comp](e *Entity) (out T) {
return out
}
func GetAllCompOfType[T Comp](e *Entity) (out []T) {
// DestroyComp calls Destroy on the component and then removes it from the entities component list
func DestroyComp[T Comp](e *Entity) {
out = []T{}
for i := 0; i < len(e.Comps); i++ {
comp, ok := e.Comps[i].(T)
if ok {
out = append(out, comp)
comp.Destroy()
e.Comps = append(e.Comps[:i], e.Comps[i+1:]...)
return
}
}
return out
}