JavaFX: Add a Perspective Camera

By Doug Lowe

The first step in creating a three-dimensional JavaFX application is adding a camera to the scene graph. You do that by creating a PerspectiveCamera object, fiddling with its settings, and then calling the scene’s setCamera method. Here’s an example:

Group root = new Group();
Scene scene = new Scene(root, 800, 800);
PerspectiveCamera camera = new PerspectiveCamera(true);

This example begins by creating a scene in the same manner as you’d create a scene for a 2D JavaFX application. Then, the example creates an instance of the PerspectiveCamera class and adjusts three properties of this class.

A perspective camera is an essential element in any 3D scene. A perspective camera represents the virtual camera that is used to render the three-dimensional world onto a flat surface. The camera is actually a part of the scene graph and has a position indicated by a set of x-, y-, z-coordinates, just like any other object in the 3D scene.

The default position for the camera (and any other object you add to the scene) is the origin point (0,0,0). So, the first thing you want to do after you add a camera is move it to a location from which it can get a good view of the objects you’ll be adding to the scene. In this example, it’s called the setTranslateZ method to back the camera away from the scene 1,000 units.

Next, set the near and far clipping distances. These values mark the range within which the camera will render objects. The near clipping distance is typically set to a very small value (in this case, 0.1) and the far clipping distance to a value large enough to contain the objects you want to appear in the scene.

After setting the clipping distances, adjust the field of view of the camera. The field of view is given as an angle and is analogous to using a wide-angle or a telephoto lens in a real camera. The default value is 30, but for this application, 35 gives a better look at the scene.

Finally, designate the camera as the scene’s active camera by calling the scene’s setCamera method.

At this stage, you have created a three-dimensional world. However, that world is a pretty lonely place, as it has no inhabitants. So from here, try to add basic 3D shapes to the world.