使用以下代码创建符合 RealityKit 物理协议(用于控制质量、速度和运动学/动力学模式)的自定义类 Physics。
物理协议的一致性层次结构如下所示:
HasPhysics: HasPhysicsBody, HasPhysicsMotion
|
|- HasCollision: HasTransform
这是一个代码:
import ARKit
import RealityKit
class Physics: Entity, HasPhysicsBody, HasPhysicsMotion {
required init() {
super.init()
self.physicsBody = PhysicsBodyComponent(massProperties: .default,
material: nil,
mode: .kinematic)
self.physicsMotion = PhysicsMotionComponent(linearVelocity: [0.1, 0, 0],
angularVelocity: [1, 3, 5])
}
}
然后在 ViewController 中创建该类的实例:
class ViewController: UIViewController {
@IBOutlet var arView: ARView!
override func viewDidLoad() {
super.viewDidLoad()
let physics = Physics()
arView.backgroundColor = .darkGray
let boxAnchor = try! Experience.loadBox()
boxAnchor.steelBox?.scale = [5, 5, 5]
let boxEntity = boxAnchor.children[0].children[0].children[0]
boxEntity.name = "CUBE"
print(boxEntity)
let kinematicComponent: PhysicsBodyComponent = physics.physicsBody!
let motionComponent: PhysicsMotionComponent = physics.physicsMotion!
boxEntity.components.set(kinematicComponent)
boxEntity.components.set(motionComponent)
arView.scene.anchors.append(boxAnchor)
}
}
另外,查看THIS POST 了解如何在没有自定义Physics 类的情况下实现物理。