Search code examples
swiftuivirtual-realityrealitykitvisionos

How can I add a PerspectiveCamera in RealityView on visionOS using RealityKit?


I want to develop a first person driving VR game. I want to programmatically move the users' view without users moving. I found PerspectiveCamera API in RealityKit. How can I add a PerspectiveCamera in RealityView to simulate driving perspective and disable Vision Pro's default perspectiveCamera?

I have tried to add a PerspectiveCamera, but it was unworkable.

RealityView { content in
    let anchorEntity = AnchorEntity(world: [0, 0, 0])
    let sphereMesh = MeshResource.generateSphere(radius: 1.5)
    let sphereMaterial = SimpleMaterial(color: .white, roughness: 0.5, isMetallic: true)
    let sphereEntity = ModelEntity(mesh: sphereMesh, materials: [sphereMaterial])
    sphereEntity.position = [0, 2, -5]
    anchorEntity.addChild(sphereEntity)

    let camera = PerspectiveCamera()
    camera.position = [1, 4, 0]
    anchorEntity.addChild(camera)
    content.add(anchorEntity)
}

Solution

  • You can use a customized PerspectiveCamera on iOS and macOS if a cameraMode property is set to .nonAR (i.e. VR mode). However, visionOS does not yet have its own ".nonAR mode" to activate a customized non-default PerspectiveCamera (even if you run a fully immersive experience).

    @available(macOS 10.15, iOS 13.0, *)
    @MainActor @preconcurrency 
    public class PerspectiveCamera : Entity, HasPerspectiveCamera {
    
        @MainActor required public init()
    }