Search code examples
javagraph3djmonkeyengine

jMonkeyEngine camera follow


I'm testing something with jMonkeyEngine and I'm attempting to have the camera follow a box spatial. I followed official instructions here:

http://jmonkeyengine.org/wiki/doku.php/jme3:advanced:making_the_camera_follow_a_character

When applying, what I learnt there I produced the following code:

@Override
public void simpleInitApp() {
    flyCam.setEnabled(false);

    //world objects
    Box b = new Box(Vector3f.ZERO, 1, 1, 1);
    Geometry geom = new Geometry("Box", b);

    Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    mat.setColor("Color", ColorRGBA.Blue);
    geom.setMaterial(mat);

    rootNode.attachChild(geom);

    //Ship node
    shipNode = new Node();
    rootNode.attachChild(shipNode);

    //Ship
    Box shipBase = new Box(new Vector3f(0, -1f, 10f), 5, 0.2f, 5);
    Geometry shipGeom = new Geometry("Ship Base", shipBase);

    Material shipMat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
    shipMat.setColor("Color", ColorRGBA.Green);
    shipGeom.setMaterial(shipMat);

    shipNode.attachChild(shipGeom);

    //Camera node
    cameraNode = new CameraNode("Camera Node", cam);
    cameraNode.setControlDir(ControlDirection.CameraToSpatial);
    shipNode.attachChild(cameraNode);

    initPhysics();

    initKeys();


}

When the following code is called:

@Override
public void simpleUpdate(float tpf) {
    //Update ship heading
    shipHeading = shipHeading.mult(shipRotationMoment);
    shipNode.setLocalRotation(shipHeading);

    shipPos = shipPos.add(shipVelocity);
    shipNode.setLocalTranslation(shipPos);
}

The box moves as is predicted but the camera stays where it is. The graph should be something like this:

  • rootNode
    • b (Box)
    • shipNode
      • shipBase
      • cameraNode

Therefore the camera should be already bound to shipNode. What am I missing?


Solution

  • Reading through the tutorial you provided, it seems you might have a typo. You have:

    cameraNode.setControlDir(ControlDirection.CameraToSpatial);
    

    However, the tutorial has:

    //This mode means that camera copies the movements of the target:
    camNode.setControlDir(ControlDirection.SpatialToCamera);
    

    Lower down in the tutorial it defines the difference between these 2 ControlDirections. The one the tutorial provides has the camera follow the movement of the object, whereas what you have the object follows the movement of the camera.

    Hope this helps.