メインコンテンツへスキップ

Examples

Hello world

  1. Create a JavaScript file (say hello-world.js).
  2. Edit it to contain the following:
import * as ecs from '@8thwall/ecs'

ecs.registerComponent({
name: 'hello-world',
add: () => {
console.log('hello world')
}
})
  1. Add your component in the hierarchy:
  2. Click ‘Run’ to see the result (a message in the developer log)

Simple schema

The following example adds three properties. Note the schemaDefaults block (lets you set default values for each property).

import * as ecs from '@8thwall/ecs'

ecs.registerComponent({
name: 'simple-schema',

schema: {
someBool: ecs.boolean,
someNumber: ecs.f64,
someString: ecs.string,
},

schemaDefaults: {
someNumber: 1000,
someString: 'go fish',
},

add: (world, component) => {
console.log('Schema someBool is', component.schema.someBool)
console.log('Schema someNumber is', component.schema.someNumber)
console.log('Schema someString is', component.schema.someString)
}
})

Tick and data

We can add a tick function that will get called every frame and a data block for tracking things from one frame to the next (it uses the same types as schema). For example:

import * as ecs from '@8thwall/ecs'

ecs.registerComponent({
name: 'tick-and-data',

data: {
tempNumber: ecs.i32,
},

...

tick: (world, component) => {
console.log('tempNumber is', component.data.tempNumber)
++component.data.tempNumber
}
})

Custom components as attributes of other components

Custom components can be added, set and modified. Example:

import * as ecs from '@8thwall/ecs'

// The handle returned by registerComponent let's us use a custom component programmatically
const numOfFishComponent = ecs.registerComponent({
name: 'num-of-fish',
schema: {
fishNum: ecs.f32,
},
...
})

// Component that adds and removes num-of-fish
ecs.registerComponent({
name: 'fish-num-tracker',
add: (world, component) => {
// Add or update num-of-fish
numOfFishComponent.set(world, component.eid, {fishNum: 5})
},
tick: (world, component) => {
...
// When no longer needed, the component can be removed
numOfFishComponent.remove(world, component.eid)
},
})