swift 自定义碰撞形状出现在错误位置

iswrvxsc  于 2023-05-05  发布在  Swift
关注(0)|答案(1)|浏览(137)

我从Reality Composer加载一个Entity,然后添加一个自定义的CollisionShape
以下是我遵循的步骤:

// I get the `.reality` url and I load the model
let rocketSceneUrl = Bundle.main.url(forResource: "Experience", 
                                   withExtension: "reality")!
                                        .appending(path: "RocketScene", 
                                          directoryHint: .notDirectory)

let rocketScene = try Entity.load(contentsOf: rocketSceneUrl)

// I get the visual bounds of the `boxScene`
let visualBounds = rocketScene.visualBounds(
                                  recursive: true, 
                                 relativeTo: self, 
                            excludeInactive: false)

// I generate the custom shape resource. 
// I use the y for the height, and half the boundingRadius
let shapeResource = ShapeResource.generateCapsule(
                                    height: bounds.extents.y, 
                                    radius: bounds.boundingRadius / 2)

// I create the custom `CollisionComponent`
let collision = CollisionComponent(
                            shapes: [shapeResource], 
                              mode: .trigger, 
                            filter: .sensor)

// I set the component on the `Entity`
rocketScene.components.set(collision)

// Then I add the `Entity` in the scene.

这就是我得到的

Entity及其碰撞形状显示在实际内容的下方,或者相反,实际内容显示在Entity及其自定义碰撞形状的上方。
我猜当RealityKit在一个表面上添加Entity时,它会通过移动内容来补偿,使它看起来像是坐在飞机上,但我可能错了。

我的问题是如何使自定义碰撞形状位于Entity内容所在的同一位置?

5jvtdoz2

5jvtdoz21#

重新定位ShapeResource的网格

自定义碰撞形状的网格正确放置在RealityKit的场景中,因为其中心与模型的轴点位置完全匹配。要重新定位shapeResource,请使用offsetBy(translation:)修改器沿着+Y方向移动它。

@MainActor func offsetBy(translation: SIMD3<Float>) -> ShapeResource

这里有一个代码:

import UIKit
import RealityKit

class ViewController: UIViewController {

    @IBOutlet var arView: ARView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
 
        arView.debugOptions = .showPhysics
        
        let entity = try! Entity.load(named: "Rocket.reality")
        
        let bounds = entity.visualBounds(recursive: true,
                                        relativeTo: nil,
                                   excludeInactive: false)
        
        var shapes: ShapeResource = ShapeResource.generateCapsule(
                                           height: bounds.extents.y,
                                           radius: bounds.boundingRadius / 2)
                                    .offsetBy(translation: [0, 0.5, 0])
                                       
        let collision = CollisionComponent(shapes: [shapes],
                                             mode: .trigger,
                                           filter: .sensor)    
        entity.components.set(collision)
        
        let anchor = AnchorEntity()
        anchor.addChild(entity)
        arView.scene.anchors.append(anchor)
    }
}

相关问题