Add Entity.With

This commit is contained in:
Trevor Slocum 2022-02-10 12:21:03 -08:00
parent 5cd926a1b2
commit 249d547332
3 changed files with 34 additions and 3 deletions

View File

@ -69,6 +69,31 @@ func (entity Entity) AddComponent(component interface{}) {
w.modifiedEntities = append(w.modifiedEntities, entity)
}
// With accepts any function which takes one or more components as arguments.
// This function will block until the provided function returns.
func (entity Entity) With(f interface{}) {
components := w.components[entity]
if components == nil {
return
}
t := reflect.TypeOf(f)
v := reflect.ValueOf(f)
numIn := t.NumIn()
if t.Kind() != reflect.Func || v.IsNil() || numIn == 0 {
panic("component.With() must be provided with a function containing one or more components as arguments")
}
args := make([]reflect.Value, numIn)
for i := 0; i < numIn; i++ {
id := componentIDByName(t.In(i).String())
args[i] = reflect.ValueOf(components[id])
}
v.Call(args)
}
// getComponent gets a Component of an Entity.
func (entity Entity) getComponent(componentID componentID) interface{} {
components := w.components[entity]

5
doc.go
View File

@ -34,8 +34,9 @@ each systems' set of required matching components.
Component Design Guidelines
Components are located in a separate package, typically named component. They
should be public (start with an uppercase letter) and may have any number of
publicly accessible data fields. They should not have any logic (i.e. game code)
should be public (start with an uppercase letter) and may be of any type.
Using only struct types (with zero or more public fields) and accessing the
structs via pointer is recommended. Components should not have any logic (i.e. game code)
within them, as all logic should be implemented within a system.
System Design Guidelines

View File

@ -8,6 +8,10 @@ import (
// System represents a system that runs continuously.
//
// Systems may specify any number of required components by adding public
// fields to their struct. When no required components are specified, the
// system will run for every active entity.
//
// While systems must implement the Update and Draw methods, the special error
// value ErrUnregister may be returned at any time by systems to indicate the
// method returning the error should not be called again.
@ -22,5 +26,6 @@ type System interface {
Draw(entity Entity, screen *ebiten.Image) error
}
// ErrUnregister is the error returned to unregister from Draw or Update events.
// ErrUnregister is a special error value which may be used to unregister a
// system from Draw or Update events.
var ErrUnregister = errors.New("unregister system")