Search code examples
javajavafx3dcamera

Create a first person camera in JavaFX


While trying to create a first person camera in javafx I tried to set the rotationAxis to a new Point3D with the translate Coordinates of the camera. That did not work so I started searching on stackoverflow, since I only recently installed javafx I am not yet comfortable with it and therefore had no idea how to even attempt to fix the problem. Anyways I found the following thread concerning the matter:

How would I make a first person camera in JavaFX 3D?

However if I copy this code and implement the proposed fix I still do not get a proper first person camera, so any help with this would be greatly appreciated.

Below is a simple example code demonstrating the problem.

package application;

import javafx.application.Application;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.SubScene;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Box;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;

public class Main extends Application {

    BorderPane pane = new BorderPane();
    Box box = new Box(150, 150, 600);
    SubScene sub = new SubScene(new Pane(box), 600, 600);
    PhongMaterial mat = new PhongMaterial(Color.RED);
    PerspectiveCamera cam = new PerspectiveCamera();

    @Override
    public void start(Stage stage) throws Exception {

        sub.setCamera(cam);

        cam.setRotationAxis(Rotate.Y_AXIS);

        box.setMaterial(mat);
        box.setManaged(false);
        box.setTranslateX(300);
        box.setTranslateY(300);
        box.setRotationAxis(Rotate.X_AXIS);
        box.setTranslateZ(100);

        stage.setScene(new Scene(pane));
        stage.sizeToScene();

        Slider slider1 = new Slider();
        slider1.valueProperty().bindBidirectional(cam.rotateProperty());

        pane.setCenter(sub);
        pane.setBottom(slider1);

        stage.centerOnScreen();
        stage.show();

    }
    public static void main(String[] args) {
        launch(args);
    }
}

Solution

  • https://github.com/FXyz/FXyz/blob/master/FXyz-Core/src/main/java/org/fxyz3d/scene/SimpleFPSCamera.java

    Its been a while since we updated it but it should get you started.