首页 > 解决方案 > RealityKit 中的第一人称体验

问题描述

我对 Swift 还很陌生,刚开始使用 RealityKit 和 ARKit。我正在做一个个人项目,我想以第一人称将 3D 对象在相机上。类似于 AR 愤怒的小鸟或任何 FPS 游戏。我在 SceneKit 或 SpriteKit 中看到了一些示例,我确信这只是对锚定实体如何工作的误解。

我的主要问题是:

下面是我的 ViewController 的代码

extension ViewController: ARSessionDelegate
{
    func session(_ session: ARSession, didUpdate frame: ARFrame)
    {
          guard let arCamera = session.currentFrame?.camera else { return }
          // Probably where I update the location of my reality experience
    }
}

class ViewController: UIViewController
{
    @IBOutlet var arView: ARView!

    override func viewDidLoad()
    {
        super.viewDidLoad()
        arView.session.delegate = self

        // Load the "ArmCannon" scene from the "Experience" Reality File
        let armCannonAnim = try! Experience.loadArmcannon()

        // Create Anchor to anchor arm cannon to
        let anchor = AnchorEntity(.camera)
        anchor.transform = arView.cameraTransform

        // Add the anchor to the scene
        arView.scene.addAnchor(anchor)

        // Setup tap gesture on arm cannon
        let tapGesture = UITapGestureRecognizer(target: self, action:#selector(onTap))
        arView.addGestureRecognizer(tapGesture)

        // Add the the cannon animation to arView
        arView.scene.anchors.append(armCannonAnim)

    }

    @IBAction func onTap(_ sender: UITapGestureRecognizer)
    {

        let tapLocation = sender.location(in: arView)

        // Get the entity at the location we've tapped, if one exists
        if let cannonFiring = arView.entity(at: tapLocation)
        {
            print(cannonFiring.name)
            print("firing Cannon")
        }
    }
}

我已经查看并阅读了使用 RealityKit 跟踪相机位置以及.camera AnchorEntity 位于何处?

标签: iosswiftarkitrealitykit

解决方案


代替:

arView.scene.anchors.append(armCannonAnim)

放:

anchor.addChild(armCannonAnim)

您需要将此 armCannonAnim 作为相机的子对象,并且该anchor对象是相机变换处的锚点。这相当于在 SceneKit 中向 cameraNode 添加一个子节点。


推荐阅读