Skip to content

jMonkeyEngine 3 Tutorial (2) - Hello Node

In a 3D game, objects such as characters and buildings need to be placed, moved and organized in a scene. This tutorial introduces the scene graph, which represents that world, and shows how Node and Geometry work together. You will create simple objects, transform them by moving, scaling and rotating them, and attach custom data such as health points.

If the scene graph is new to you, start with The Scene Graph or the visual introduction in Scene Graph for Dummies.

Code Sample

package jme3test.helloworld;

import com.jme3.app.SimpleApplication;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.shape.Box;

/** Sample 2 - How to use nodes as handles to manipulate objects in the scene.
 * You can rotate, translate, and scale objects by manipulating their parent nodes.
 * The Root Node is special: Only what is attached to the Root Node appears in the scene. */
public class HelloNode extends SimpleApplication {

    public static void main(String[] args){
        HelloNode app = new HelloNode();
        app.start();
    }

    @Override
    public void simpleInitApp() {

        /** create a blue box at coordinates (1,-1,1) */
        Box box1 = new Box(1,1,1);
        Geometry blue = new Geometry("Box", box1);
        blue.setLocalTranslation(new Vector3f(1,-1,1));
        Material mat1 = new Material(assetManager,
                "Common/MatDefs/Misc/Unshaded.j3md");
        mat1.setColor("Color", ColorRGBA.Blue);
        blue.setMaterial(mat1);

        /** create a red box straight above the blue one at (1,3,1) */
        Box box2 = new Box(1,1,1);
        Geometry red = new Geometry("Box", box2);
        red.setLocalTranslation(new Vector3f(1,3,1));
        Material mat2 = new Material(assetManager,
                "Common/MatDefs/Misc/Unshaded.j3md");
        mat2.setColor("Color", ColorRGBA.Red);
        red.setMaterial(mat2);

        /** Create a pivot node at (0,0,0) and attach it to the root node */
        Node pivot = new Node("pivot");
        rootNode.attachChild(pivot); // put this node in the scene

        /** Attach the two boxes to the *pivot* node. (And transitively to the root node.) */
        pivot.attachChild(blue);
        pivot.attachChild(red);
        /** Rotate the pivot node: Note that both boxes have rotated! */
        pivot.rotate(.4f,.4f,0f);
    }
}

Build and run the code sample. You should see two colored boxes tilted at the same angle.

Understanding the Terminology

In this tutorial, you learn some new terms:

What you want to do? How you say it in JME3 terminology
Lay out the 3D scene. Populate the scene graph.
Create scene objects. Create Spatials. (e.g. create Geometries)
Make an object appear in the scene. Attach a Spatial to the rootNode.
Make an object disappear from the scene. Detach the Spatial from the rootNode.
Position/move, turn, or resize an object. Translate, or rotate, or scale an object = transform an object.

When you extend SimpleApplication, your game inherits its rootNode object. Everything attached to the rootNode is part of the scene graph. The elements of the scene graph are Spatials.

  • A Spatial contains the location, rotation, and scale of an object.

  • A Spatial can be loaded, transformed, and saved.

  • There are two types of Spatials: Nodes and Geometries.

Geometry Node
Visibility: A Geometry is a visible scene object. A Node is an invisible “handle” for scene objects.
Purpose: A Geometry stores an object’s looks. A Node groups Geometries and other Nodes together.
Examples: A box, a sphere, a player, a building, a piece of terrain, a vehicle, missiles, NPCs, etc… The rootNode, a floor node grouping several terrains, a custom vehicle-with-passengers node, a player-with-weapon node, an audio node, etc…

Understanding the Code

What happens in the code snippet? You use the simpleInitApp() method that was introduced in the first tutorial to initialize the scene.

  1. You create the first box Geometry.

    • Create a Box shape with extents of (1,1,1), that makes the box 2x2x2 world units big.

    • Position the box at (1,-1,1) using the setLocalTranslation() method.

    • Wrap the Box shape into a Geometry.

    • Create a blue material.

    • Apply the blue material to the Box Geometry.

        Box box1 = new Box(1,1,1);
        Geometry blue = new Geometry("Box", box1);
        blue.setLocalTranslation(new Vector3f(1,-1,1));
        Material mat1 = new Material(assetManager,"Common/MatDefs/Misc/Unshaded.j3md");
        mat1.setColor("Color", ColorRGBA.Blue);
        blue.setMaterial(mat1);
    
  2. You create a second box Geometry.

    • Create a second Box shape with the same size.

    • Position the second box at (1,3,1). This is straight above the first box, with a gap of 2 world units inbetween.

    • Wrap the Box shape into a Geometry.

    • Create a red material.

    • Apply the red material to the Box Geometry.

        Box box2 = new Box(1,1,1);
        Geometry red = new Geometry("Box", box2);
        red.setLocalTranslation(new Vector3f(1,3,1));
        Material mat2 = new Material(assetManager,
          "Common/MatDefs/Misc/Unshaded.j3md");
        mat2.setColor("Color", ColorRGBA.Red);
        red.setMaterial(mat2);
    
  3. You create a pivot Node.

    • Name the Node “pivot”.

    • By default the Node is positioned at (0,0,0).

    • Attach the Node to the rootNode.

    • The Node has no visible appearance in the scene.

        Node pivot = new Node("pivot");
        rootNode.attachChild(pivot);
    

    If you run the application with only the code up to here, the scene appears empty. This is because a Node is invisible, and you have not yet attached any visible Geometries to the rootNode.

  4. Attach the two boxes to the pivot node.

            pivot.attachChild(blue);
            pivot.attachChild(red);
    

    If you run the app with only the code up to here, you see two cubes: A red cube straight above a blue cube.

  5. Rotate the pivot node.

            pivot.rotate( 0.4f , 0.4f , 0.0f );
    

If you run the app now, you see two boxes on top of each other – both tilted at the same angle.

What is a Pivot Node?

You can transform (e.g. rotate) Geometries around their own center, or around a user defined center point. A user defined center point for one or more Geometries is called a pivot.

In this example, you have grouped two Geometries by attaching them to one pivot Node. You use the pivot Node as a handle to rotate the two Geometries together around one common center. Rotating the pivot Node rotates all attached Geometries, in one step. The pivot node is the center of the rotation. Place the pivot node at the point about which its children should rotate. In this example the pivot starts at (0,0,0). Transforming a parent Node to transform all attached child Spatials is a common task. You will use this method a lot in your games when you move Spatials around.

Examples: A vehicle and its driver move together; a planet with its moon orbits the sun.

Contrast this case with the other option. If you don’t create an extra pivot node and transform a Geometry, then every transformation is done relative to the Geometry’s origin (typically the center).

Examples: If you rotate each cube directly (using red.rotate(0.1f , 0.2f , 0.3f); and blue.rotate(0.5f , 0.0f , 0.25f);), then each cube is rotated individually around its center. This is similar to a planet rotating around its own center.

How do I Populate the Scene Graph?

Create a mesh, wrap it in a geometry, give it a material, and attach it to the scene:

Box mesh = new Box(1, 1, 1);
Geometry thing = new Geometry("thing", mesh);
Material mat = new Material(assetManager, "Common/MatDefs/Misc/ShowNormals.j3md");
thing.setMaterial(mat);
rootNode.attachChild(thing);

A spatial can be attached to any node that is itself part of the scene. To remove a child, detach it from its parent; detachAllChildren() removes all children of that particular node.

rootNode.detachChild(thing);
// Or remove all direct children:
rootNode.detachAllChildren();

Find a descendant by name, a direct child by index, or inspect a spatial's parent:

Spatial named = rootNode.getChild("thing");
Spatial twentyThird = rootNode.getChild(22); // only if there are at least 23 children
Node parent = myNode.getParent();

A name lookup searches descendants and can return null; an index must be in range. Objects initialized and attached in simpleInitApp() are present at the start of the application.

How do I Transform Spatials?

A spatial's local translation, rotation and scale are relative to its parent. To set a position or move by an offset:

thing.setLocalTranslation(new Vector3f(0f, 40.2f, -2f));
thing.move(0f, 40.2f, -2f);

The usual axes are X for left/right, Y for down/up and Z for depth. A positive or negative axis direction does not by itself determine the camera's forward direction.

Scale factors multiply the current scale. For example, stretch X tenfold, shrink Y to one tenth and leave Z unchanged:

thing.scale(10f, 0.1f, 1f);

Values between zero and one shrink a dimension; values above one enlarge it. Equal factors keep proportions. For an absolute local scale use setLocalScale().

Rotations use radians. Multiply degrees by FastMath.DEG_TO_RAD when needed:

thing.rotate(0f, 0f, 180 * FastMath.DEG_TO_RAD);

For a specified local orientation, use a quaternion. This example sets a half-turn around the X axis:

thing.setLocalRotation(new Quaternion().fromAngleAxis(
        180 * FastMath.DEG_TO_RAD, Vector3f.UNIT_X));

See rotations and quaternions for more detail.

How do I Troubleshoot Spatials?

  • If a geometry is invisible, check its material, its position and size, the camera direction and whether it is attached to a scene root rendered by a viewport. Also check the camera's near and far clipping planes.
  • If a spatial rotates unexpectedly, check the units (radians), axis and pivot, and consider its parent transform.
  • If a material changes on several geometries, check whether they share the same Material instance. Clone it when you need independent properties.

How do I Add Custom Data to Spatials?

Many Spatials represent game characters or other entities that the player can interact with. The above code that rotates the two boxes around a common center (pivot) could be used for a spacecraft docked to a orbiting space station, for example.

Depending on your game, game entities do not only change their position, rotation, or scale (the transformations that you just learned about). Game entities also have custom properties, such as health, inventory carried, equipment worn for a character, or hull strength and fuel left for a spacecraft. In Java, you represent entity data as class variables, e.g. floats, Strings, or Arrays.

You can add custom data directly to any Node or Geometry. You do not need to extend the Node class to include variables! For example, to add a custom id number to a node, you would use:

pivot.setUserData( "pivot id", 42 );

To read this Node’s id number elsewhere, you would use:

int id = pivot.getUserData( "pivot id" );

By using different Strings keys (here the key is pivot id), you can get and set several values for whatever data the Spatial needs to carry. When you start writing your game, you might add a fuel value to a car node, speed value to an airplane node, or number of gold coins to a player node, and much more. User data must be a supported type; for custom objects, implement Savable and verify save/load behavior.

Conclusion

You have learned that your 3D scene is a scene graph made up of Spatials: Visible Geometries and invisible Nodes. You can transform Spatials, or attach them to nodes and transform the nodes. You know the easiest way how to add custom entity properties (such as player health or vehicle speed) to Spatials.