Skip to content

jMonkeyEngine 3 Tutorial (7) - Hello Animation

Example model

This example uses Models/Oto/Oto.j3o from the separate jme3-testdata module. Add that module to your project or adapt the example to your own model.

This tutorial shows how to add an animation controller and how to respond to user input by triggering an animation in a loaded model.

beginner-animation.png

Tip

Some examples use assets from the separate org.jmonkeyengine:jme3-testdata module. Check the engine version catalog for a compatible test-data version, or supply equivalent assets and update their paths.

Sample Code

package jme3test.helloworld;

import com.jme3.anim.AnimComposer;
import com.jme3.anim.tween.Tween;
import com.jme3.anim.tween.Tweens;
import com.jme3.anim.tween.action.Action;
import com.jme3.anim.tween.action.BlendSpace;
import com.jme3.anim.tween.action.LinearBlendSpace;
import com.jme3.app.SimpleApplication;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.light.DirectionalLight;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;

/** Sample 7 - how to load a model and play an animation,
 * using AnimComposer */
public class HelloAnimation extends SimpleApplication{

    private AnimComposer control;
    private Action advance;

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

    @Override
    public void simpleInitApp() {
        viewPort.setBackgroundColor(ColorRGBA.LightGray);
        initKeys();
        DirectionalLight dl = new DirectionalLight();
        dl.setDirection(new Vector3f(-0.1f, -1f, -1).normalizeLocal());
        rootNode.addLight(dl);
        player = (Node) assetManager.loadModel("Models/Oto/Oto.j3o");
        player.setLocalScale(0.5f);
        rootNode.attachChild(player);
        control = player.getControl(AnimComposer.class);
        control.setCurrentAction("stand");

        /* Compose an animation action named "halt"
        that transitions from "Walk" to "stand" in half a second. */
        BlendSpace quickBlend = new LinearBlendSpace(0f, 0.5f);
        Action halt = control.actionBlended("halt", quickBlend, "stand", "Walk");
        halt.setLength(0.5);

        /* Compose an animation action named "advance"
        that walks for one cycle, then halts, then invokes onAdvanceDone(). */
        Action walk = control.action("Walk");
        Tween doneTween = Tweens.callMethod(this, "onAdvanceDone");
        advance = control.actionSequence("advance", walk, halt, doneTween);
    }

    /**
     * Callback to indicate that the "advance" animation action has completed.
     */
    void onAdvanceDone() {
        /*
         * Play the "stand" animation action.
         */
        control.setCurrentAction("stand");
    }

    /**
     * Map the spacebar to the "Walk" input action, and add a listener to initiate
     * the "advance" animation action each time it's pressed.
     */
    private void initKeys() {
        inputManager.addMapping("Walk", new KeyTrigger(KeyInput.KEY_SPACE));

        ActionListener handler = new ActionListener() {
            @Override
            public void onAction(String name, boolean keyPressed, float tpf) {
                if (keyPressed && control.getCurrentAction() != advance) {
                    control.setCurrentAction("advance");
                }
            }
        };
        inputManager.addListener(handler, "Walk");
    }
}

Creating and Loading Animated Models

You create animated models with a tool such as Blender. Take some time and learn how to create your own models in these Blender Animation Tutorials. For now, download and use a free model, such as the one included here as an example (Oto Golem and Ninja are included in the jme-testdata project).

The runnable example uses the Oto .j3o model from jme3-testdata, which contains the stand and Walk clips used below. You can also load an animated glTF model: adjust the asset path and action names to match its clips. A .glb can contain its mesh, skin, animations and materials together; a .gltf may refer to separate files that must remain alongside it.

  public void simpleInitApp() {
    /* Displaying the model requires a light source */
    DirectionalLight dl = new DirectionalLight();
    dl.setDirection(new Vector3f(-0.1f, -1f, -1).normalizeLocal());
    rootNode.addLight(dl);
    /* load and attach the model as usual */
    player = (Node) assetManager.loadModel("Models/Oto/Oto.j3o");
    player.setLocalScale(0.5f); // resize
    rootNode.attachChild(player);
    ...
    }

Don’t forget to add a light source to make the material visible.

Animation Composer and Layers

The loaded model contains an AnimComposer control. Retrieve it from the spatial that owns it to play animation actions.

  • The composer gives you access to the available animation clips and actions.
  • Its default layer runs the action selected by setCurrentAction.
  • You can create additional named layers and animation masks when you need to combine actions on different parts of a model.
  private AnimComposer control;

  public void simpleInitApp() {
    ...
    /* Find the composer and start the model’s standing action. */
     control = player.getControl(AnimComposer.class);
     control.setCurrentAction("stand");
    ...
}

This line of code will return NULL if the AnimComposer is not in the main node of your model.

control = player.getControl(AnimComposer.class);

Inspect the model’s scene graph to locate the spatial that owns the control. For a known child, retrieve the control from that child; check for null if the model structure is not guaranteed:

player.getChild("Subnode").getControl(AnimComposer.class);

Responding to Animation Events

A Tween (part of an action sequence) can call a method on a class, allowing your application code to be informed of the animation state. In this example, you reset the character to a standing position after a Walk cycle is done.

public class HelloAnimation extends SimpleApplication {
  ...

      @Override
    public void simpleInitApp() {
      ...
      Action walk = control.action("Walk");
      Tween doneTween = Tweens.callMethod(this, "onAdvanceDone");
      advance = control.actionSequence("advance", walk, halt, doneTween);
      ...
    }

    /**
     * Callback to indicate that the "advance" animation action has completed.
     */
    void onAdvanceDone() {
        /*
         * Play the "stand" animation action.
         */
        control.setCurrentAction("stand");
    }
 ...
}

Trigger Animations After User Input

There are ambient animations like animals or trees that you may want to trigger in the main event loop. In other cases, animations are triggered by user interaction, such as key input. You want to play the Walk animation when the player presses a certain key (here the spacebar), to play the avatar’s walking animation. Moving the character through the world is a separate task unless your game explicitly applies root motion.

  1. Initialize a new input controller (in simpleInitApp()).

    • Write the initKeys() convenience method and call it from simpleInitApp().
  2. Add a key mapping with the name as the action you want to trigger.

    • Here for example, you map Walk to the Spacebar key.
  3. Add an input listener for the Walk action.

    /**
     * Map the spacebar to the "Walk" input action, and add a listener to initiate
     * the "advance" animation action each time it's pressed.
     */
    private void initKeys() {
        inputManager.addMapping("Walk", new KeyTrigger(KeyInput.KEY_SPACE));

        ActionListener handler = new ActionListener() {
            @Override
            public void onAction(String name, boolean keyPressed, float tpf) {
                if (keyPressed && control.getCurrentAction() != advance) {
                    control.setCurrentAction("advance");
                }
            }
        };
        inputManager.addListener(handler, "Walk");
    }
  • By default, the animation will loop, there is an overloaded setCurrentAction method that allows you to set the loop mode.

  • If needed, use Action::setSpeed to set the speed of this animation.

  • Optionally, use AnimComposer::.setTime to Fast-forward or rewind to a certain moment in time of this animation.

Exercises

Exercise 1: Two Animations

Make a mouse click trigger another animation sequence!

  1. Create a second layer in the controller.

  2. Create a new key trigger mapping and action. (see: Hello Input)

    Tip

    Do you want to find out what animation sequences are available in the model?

    Use:

    for (String anim : control.getAnimClipsNames()) {
        System.out.println(anim);
    }
    

Exercise 2: Revealing the Skeleton (1)

Inspect the armature of your animated model in your modeling tool. You can also list the available animation clips with control.getAnimClipsNames(). Look for these features:

  • Note how the bones are numbered and named. All names of animated models follow a naming scheme.

  • Note the bone hierarchy that specifies how the bones are connected.

  • Note the list of animations: Each animation has a name, and several tracks. Each track tells individual bones how and when to transform. These animation steps are called keyframes.

Exercise 3: Revealing the Skeleton (2)

Add the following imports for the armature debug state and skinning control:

     import com.jme3.scene.debug.custom.ArmatureDebugAppState;
     import com.jme3.anim.SkinningControl;

Add the following code snippet to simpleInitApp() to make the bones (that you just read about) visible!

    ArmatureDebugAppState armatureDebugAppState = new ArmatureDebugAppState();
    armatureDebugAppState.addArmatureFrom(player.getControl(SkinningControl.class));
    this.getStateManager().attach(armatureDebugAppState);

Can you identify individual bones in the skeleton? If getControl(SkinningControl.class) returns null, locate the spatial that owns the skinning control and retrieve it there.

Conclusion

Now you can load animated models, identify stored animations and play actions with AnimComposer. You also learned that you can combine animations using layers. This could be useful if you ever want to animate the lower and upper part of the characters body independently, for example the legs run, while the arms use a weapon.