カスタム・コンポーネント
はじめに
カスタムコンポーネントは、視覚的な外観、物理的なプロパティ、入力処理、またはカスタムゲームロジックを定義します。カスタムコンポーネントの作成
カスタムコンポーネントを作成するには、以下の手順に従います:
- ファイルブラウザでプラスボタン(+)をクリックする。
- 新規ファイル」→「新規コンポーネントファイル」をクリックし、名前を付ける(拡張子は任意)。
- 新しいComponentファイルが生成され、デフォルトではプロジェクト内にTypeScriptが生成される。
- 新しいComponentファイルには、カスタムComponentの登録に必要な定型コードが含まれます。
カスタムコンポーネントの登録
次のコードは、新しく作成されたカスタムコンポーネントがコードエディターに表示される例です:
例
危険
コンポーネント名の接頭辞として「debug-」を使用するのは避けること。 debug-'で始まるコンポーネント名は、内部デバッグのために予約されており、**あなたのコードで使用すると正しく機能しません。
// これはComponentファイルです。このファイルを使用して、プロジェクトのカスタムComponentを定義することができます。
//
import * as ecs from '@8thwall/ecs' // これがecsライブラリにアクセスする方法です。
ecs.registerComponent({
name: 'custom-component',
schema: {
// Component上で設定可能なデータを追加します。
},
schemaDefaults: {
// スキーマフィールドのデフォルトを追加する。
},
data: {
// Componentの外部で設定できないデータを追加します。
},
add: (world, component) => {
// Componentがワールドに追加されたときに実行されます。
},
tick: (world, component) => {
// 毎フレーム実行。
},
remove: (world, component) => {
// Componentが世界から削除されたときに実行されます。
},
})
エンティティにカスタム・コンポーネントを追加する
次の例は、既存のエンティティにカスタムコンポーネントを追加する方法を示しています。
例
tip
コンポーネントをインポートまたは使用する前に、必ずコンポーネントをエクスポートしてください。
import * as ecs from '@8thwall/ecs'
const CustomComponent = ecs.registerComponent({
name: 'custom-component',
schema: {
foo: ecs.string
},
schemaDefaults: {
},
data: {
},
add: (world, component) => {
},
tick: (world, component) => {
},
remove: (world, component) => {
},
})
export {CustomComponent}
import CustomComponent from './custom-component' // ファイル・タイプを除いたファイル名。
const demo = world.createEntity()
CustomComponent.set(world, demo, {
foo: 'bar'
})
関数一覧
コンポーネント関数を使用すると、エンティティに関連するコンポーネントとそのデータに対して、さまざまなアクションを実行できます。
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) => {
カーソル.半径 += 1;
カーソル.高さ *= 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)