Multiple Cameras in VisionOS Previews
If you’ve had a play around with the Preview of Vision content within Xcode, you’ll know how powerful it can be to see instant feedback for changes you’re making in code. It’s a particular impressive experience, given the complexities of 3D content that can be shown, in near real time.
However if like me you’ll also quickly become frustrated with how cumbersome it can be to navigate the simulated world, particularly if you have to move around your content regularly to validate the effect your trying to create. There are a number of built in cameras to the preview that you can jump between, but what if you need a specific angle not covered by these?
That’s where preview cameras come in, which were introduced in Xcode 15.0 beta 3. With the new #Preview macro, you are able to define your own PreviewCamera’s with options for setting a direction, or more usefully setting a camera location, looking towards another location.
To use these camera previews, you will ned to add them to the #Preview macro as follows:
BEFORE:
#Preview {
MyModelView()
}
AFTER:
#Preview(body: {
MyModelView()
}, cameras: {
PreviewCamera(from: .topTrailingFront,
zoom: 0.5,
name: "cam0")
PreviewCamera(lookingAt: Point3D(x: 0, y: -1, z: 2),
from: Point3D(x: 1, y: 0, z: 2),
name: "cam1")
})
Here we’re creating two Preview Cameras. The first is using a UnitPoint3D, to specify a position to look down on the content from, whilst also zooming out from the content. The second is a more flexible way to define a camera. It’s looking at a point that is near the ground and a 2m away from the back wall of the room (which seems to be the 0 position), with the camera’s position (“from”) being 1m to the side, and on the ceiling (defined as 0m). With the second option, you don’t have the ability to set the zoom level specifically.
When you start the preview, it will now use the first camera you set as the PreviewCamera, but you can switch between them easily using the camera button in the lower right of the Preview Canvas.
You can add as many camera’s as you like, just be sure to give them a unique name so that you can differentiate them in the UI.
Happy Viewing!