swift - 如何旋转并向从 Reality Composer 加载的实体添加线性力?

标签 swift augmented-reality arkit realitykit reality-composer

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

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

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

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

最佳答案

使用以下代码创建符合 RealityKit 物理协议(protocol)(用于控制质量、速度和运动学/动力学模式)的自定义类 Physics

物理协议(protocol)的一致性层次结构如下所示:

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)
    }
}

enter image description here


另外,看看 THIS POST了解如何在没有自定义 Physics 类的情况下实现物理。


enter image description here

关于swift - 如何旋转并向从 Reality Composer 加载的实体添加线性力?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61163705/

相关文章:

swift - map 按钮刷新位置

java - ARCore Android SDK – 如何在Transformable节点上制作缩放动画?

opencv - 简历透视变换: What am I supposed to provide?

ios - ARKit : How to apply material with multiple colors for SCNCylinder in SCNView?

swift - 检测用户是否向左或向右移动手指(Swift)

constants - "let"关键字在 Swift 中究竟是如何工作的?

swift - 搜索栏 textDidChange 错误

javascript - 通过相机旋转计算平面上的 x z 运动

ios - ARKit仅检测地板来放置物体

swift - SCNReferenceNode 中没有可用的 SCNGeometry?