【问题标题】:How do I spin and add a linear force to an Entity loaded from Reality Composer?如何旋转并向从 Reality Composer 加载的实体添加线性力?
【发布时间】:2020-07-24 14:01:43
【问题描述】:

我在 Reality Composer 中构建了一个场景,其中有一个球,该球开始漂浮在空中的场景。我试图在旋转的同时以编程方式扔球。

我尝试通过 Reality Composer 中的行为来做到这一点,但无法让这两种行为同时工作,而且一旦我开始动画,球就会立即落到地上。

我的第二次尝试是放弃行为路线,我尝试以编程方式执行此操作,但我无法添加力,因为加载的球是实体而不是 ModelEntity。我做错了什么?

我想同时旋转球、施加力和启用重力。

【问题讨论】:

    标签: swift augmented-reality arkit realitykit reality-composer


    【解决方案1】:

    要添加力,您需要实体符合 HasPhysicsMotion。要查看从 RC 导入的实体是否可以对其施加力,请检查 (myEntity as?HasPhysics) 是否返回 nil 或值。

    如果返回 nil,则创建您自己的具有 HasPhysics 协议的实体子类,并将您的实体设置为它的子实体。如果您希望它与场景中的其他事物发生碰撞,那么您还需要 HasCollision 协议。

    你提到的所有事情都可以从这一点实现!

    【讨论】:

    【解决方案2】:

    使用以下代码创建符合 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 类的情况下实现物理。


    【讨论】:

    • 感谢您的帮助安迪。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多