实体
实体(Entity)表示三维场景中的一个对象,可以被创建、销毁,也可以动态的添加或删除组件(Component)。
提示
实体自身不具有任何特性和能力,需要通过添加组件为实体增加特性和能力。
实体属性
guid - 实体唯一标识,只读属性。
name - 实体名称,读写属性。
activeSelf - 实体的本地激活状态,只读属性。
注意
即使 activeSelf 返回 true,如果父实体处于非激活状态,则该实体也处于非激活状态。如果要检查实体在场景中是否处于激活状态,请使用 activeInHierarchy。
activeInHierarchy - 定义实体在场景中是否处于激活状态。
重要
Transform 组件不需要手动添加,实体始终附加一个变换组件,也不要主动移除变换组件。
userData - 实体用户数据,读写属性。
scene - 获取实体所属场景,只读属性。
isRoot - 判断是否是场景根实体,只读属性。
visible - 设置实体是否可见,只写属性。
children - 获取实体的所有子实体,只读属性。
实体方法
- setActive - 激活或停用实体。
提示
实体处于非激活状态如果其父实体未激活。在这种情况下,调用 setActive 不会激活实体,只会将 activeSelf 设置为 true。
- createChild - 创建一个子实体。
// 创建子实体
const child = entity.createChild();
重要
实体只有作为场景根实体的后代才会被渲染。
import { Vector3 } from 'three';
// 获取场景根实体
const { rootEntity } = scene;
// 创建一个新实体作为根实体的“儿子”
const son = rootEntity.createChild( { transform: { position: new Vector3( 10.0, 0.0, 35.0 ) } } );
// 创建一个新实体作为根实体的“孙子”
const grandson = son.createChild();
addChild - 添加一个子实体。
removeChild - 移除一个子实体。
removeAllChildren - 移除所有子实体。
removeFromParent - 从父实体子实体中移除该实体。
addComponent - 添加一个组件。
hasComponent - 判断实体是否已添加指定类型组件。
getComponent - 获取指定类型组件。
getAllComponents - 获取实体上的所有组件。
removeComponent - 移除指定类型组件。
removeAllComponents - 移除所有组件。
getLocalBounds - 获取实体本地外包范围。
getWorldBounds - 获取实体世界外包范围。
destroy - 销毁实体。
注意
该方法会销毁实体及其所有后代实体!
- findByGUID - 通过GUID查找实体,静态方法。
import { Entity } from '@fantasy3d/core';
// 从场景根实体开始查找
const entity = Entity.findByGUID( rootEntity, '2ddf2a22-d123-48f8-875e-f1beae7f3391' );
- findByName - 通过名称查找实体,静态方法。
import { Entity } from '@fantasy3d/core';
// 从场景根实体开始查找所有名字为"汽车"的实体
const entities = Entity.findByName( rootEntity, '汽车' );
- findByComponent - 通过组件查找实体,静态方法。
import { Entity, MeshRenderer } from '@fantasy3d/core';
// 从场景根实体开始查找所有添加MeshRenderer组件的实体
const entities = Entity.findByComponent( rootEntity, MeshRenderer );
- findByCondition - 通过自定义条件查找实体,静态方法。
import { Entity, defined } from '@fantasy3d/core';
// 从场景根实体开始查找满足条件的所有实体
const entities = Entity.findByCondition( rootEntity, ( entity ) => {
const { userData } = entity;
const { layer } = userData;
if ( defined( layer ) && layer === '矢量' ) {
return true;
}
return false;
} );
- traverse - 递归遍历实体及其后代实体,静态方法。
import { Entity } from '@fantasy3d/core';
// 从场景根实体开始递归遍历
Entity.traverse( rootEntity, ( entity ) => {
// TODO:
} );
重要
不要在实体递归遍历回调中调用实体销毁(destroy)接口!!!
实体事件
重要
“取消订阅”时如果不指定第二个参数,会取消该类型事件的所有订阅!
- emit - 分发事件。