The design of RealityKit follows a pattern called Entity Component System (ECS). In ECS, functionality for virtual objects, known as entities, exists on separate components that are added to entities to give them different abilities or behaviors. Components encapsulate logic in a generic way that can be utilized by any entity. This design keeps entities lightweight by including only the components they need.
In RealityKit, add components to an entity by conforming it to a protocol. For example, the PhysicsBodyComponent, which encapsulates the logic needed for an object to participate in RealityKit's physics simulation, has a corresponding protocol called HasPhysicsBody. Entities that conform to HasPhysicsBody automatically simulate physics without writing any additional code. To check if an entity has a particular component, cast it to the protocol. If the cast returns nil, the entity doesn't have that component.
RealityKit的设计遵循一种称为实体组件系统(ECS)的模式。在ECS中,虚拟对象的功能(称为实体)存在于添加到实体的独立组件中,以赋予实体不同的能力或行为。组件以一种通用的方式封装逻辑,任何实体都可以使用这种方式。这种设计通过只包含实体需要的组件来保持实体的轻量级。
在RealityKit中,通过使实体遵循协议来向其添加组件。例如,PhysicsBodyComponent封装了一个对象参与RealityKit的物理模拟所需的逻辑,它有一个对应的协议叫做HasPhysicsBody。符合HasPhysicsBody的实体无需编写任何额外代码就能自动模拟物理。要检查实体是否有特定的组件,请将其转换为协议。如果转换返回nil,则实体没有该组件。
guard let entity = entity as? HasPhysicsBody else { return }