实体和组件
可参考的官方例子:
ecs_guide
.
实体 Entities
实体只是一个简单的整数 ID,它标识了一组特定的组件值。
要创建("spawn")新的实体,请使用 Commands
。
组件 Components
组件是实体关联的数据。
要创建一个新的组件类型,只需定义一个 Rust 结构
或枚举
,并派生 Component
trait。
#[derive(Component)]
struct Health {
hp: f32,
extra: f32,
}
组件类型必须是唯一的,Rust 的每种类型中只能对应一个组件。
使用 newtype
模式来包装数据类型,从基本类型中制作出独特的组件:
#[derive(Component)]
struct PlayerXp(u32);
#[derive(Component)]
struct PlayerName(String);
你可以使用空结构体来帮助你识别特定的实体。这些被称为"标记组件"。对[查询过滤器][cb::queryfilter]非常有用。
/// Add this to all menu ui entities to help identify them
#[derive(Component)]
struct MainMenuUI;
/// Marker for hostile game units
#[derive(Component)]
struct Enemy;
/// This will be used to identify the main player entity
#[derive(Component)]
struct Player;
你可以使用 Commands
在现有实体上添加/删除组件。
组件 Bundle
Bundle 就像"模板"一样,使创建具有共同组件集的实体变得容易。
#[derive(Bundle)]
struct PlayerBundle {
xp: PlayerXp,
name: PlayerName,
health: Health,
_p: Player,
// We can nest/include another bundle.
// Add the components for a standard Bevy Sprite:
#[bundle]
sprite: SpriteSheetBundle,
}
Bevy 也将具有任意组件的元组视为 Bundle。
(ComponentA, ComponentB, ComponentC)
请注意,你不能查询整个 Bundle。Bundle 只是作为创建实体时的一种便捷方式,你仍需要在你的系统中单独地查询你想要访问的组件类型。