Funktionen der Komponenten
Einführung
Komponenten können während der Laufzeit hinzugefügt, geändert und entfernt werden. Eingebaute Komponenten und benutzerdefinierte Komponenten verwenden dieselbe Schnittstelle für die Verwaltung von Komponentendaten.
Referenzieren einer benutzerdefinierten Komponente
Das folgende Beispiel zeigt, wie ein Verweis auf eine benutzerdefinierte Komponente zwischen verschiedenen Codedateien ausgetauscht werden kann.
Stellen Sie sicher, dass Sie die Komponente exportieren, bevor Sie versuchen, sie zu importieren oder irgendwo zu verwenden.
import * as ecs from '@8thwall/ecs'
const CustomComponent = ecs.registerComponent({
...
})
export {CustomComponent}
import * as ecs from '@8thwall/ecs'
import {CustomComponent} from './custom-component'
ecs.registerComponent({
name: 'Another Custom Component',
stateMachine: ({world, eid, schemaAttribute, dataAttribute}) => {
ecs.defineState('default')
.initial()
.onEnter(() => {
const entity = world.createEntity()
CustomComponent.set(world, entity, {
displayName: 'Jini'
})
})
},
})
Funktionen
Mit Komponentenfunktionen können Sie verschiedene Aktionen für eine Komponente und ihre Daten in Bezug auf eine Entität durchführen.
Get
Returns a read-only reference.
Example
ecs.CylinderGeometry.get(world, component.eid)
Set
Ensures the component exists on the entity, then assigns the (optional) data to the component.
Example
ecs.CylinderGeometry.set(world, component.eid, {
radius: 1,
height: 1
})
Mutate
Perform an update to the component within a callback function. Return true
to indicate no changes made.
Example
ecs.CylinderGeometry.mutate(world, component.eid, (cursor) => {
cursor.radius += 1;
cursor.height *= 2;
return false;
})
Remove
Removes the component from the entity.
Example
ecs.CylinderGeometry.remove(world, component.eid)
Has
Returns true
if the component is present on the entity.
Example
ecs.CylinderGeometry.has(world, component.eid)
Reset
Adds, or resets the component to its default state.
Example
ecs.CylinderGeometry.reset(world, component.eid)
Advanced Functions
Cursor
Returns a mutable reference. Cursors are reused so only one cursor for each component can exist at a time.
Example
ecs.CylinderGeometry.cursor(world, component.eid)
Acquire
Same behavior as cursor, but commit must be called after the cursor is done being used.
Example
ecs.CylinderGeometry.acquire(world, component.eid)
Commit
Called after acquire. An optional third argument determines whether the cursor was mutated or not.
Example
ecs.CylinderGeometry.commit(world, component.eid)
ecs.CylinderGeometry.commit(world, component.eid, false)
Dirty
Mark the entity as having been mutated. Only needed in a specific case where systems are mutating data.
Example
ecs.CylinderGeometry.dirty(world, component.eid)