Skip to content

Custom Controls

A com.jme3.scene.control.Control is a customizable jME3 interface that allows you to cleanly steer the behaviour of game entities (Spatials), such as artificially intelligent behaviour in NPCs, traps, automatic alarms and doors, animals and pets, self-steering vehicles or platforms – anything that moves and interacts. Several instances of custom Controls together implement the behaviours of a type of Spatial.

To control global game behaviour see AppStates – you often use AppStates and Control together.

To control the behaviour of spatials:

  1. Create one control for each type of behavior. When you add several controls to one spatial, they will be executed in the order they were added.

    For example, one NPC can be controlled by a PhysicsControl instance and an AIControl instance.

  2. Define the custom control and implement its behaviour in the Control’s update method:

    • You can pass arguments into your custom control.

    • In the control class, the object spatial gives you access to the spatial and subspatials that the control is attached to.

    • Here you modify the spatial’s transformation (move, scale, rotate), play animations, check its environment, define how it acts and reacts.

  3. Add an instance of the Control to a spatial to give it this behavior. The spatial’s game state is updated automatically from now on.

spatial.addControl(myControl);

To implement game logic for a type of spatial, you will either extend AbstractControl (most common case), or implement the Control interface, as explained in this article.

Usage

Use Controls to implement the behaviour of types of game entities.

  • Use Controls to add a type of behaviour (that is, methods and fields) to individual Spatials.

  • The scene graph invokes each attached Control’s update() during its logical update, after simpleUpdate() in a SimpleApplication. Use Controls to move blocks of code out of the simpleUpdate() loop.

  • One Spatial can be influenced by several Controls. (Very powerful and modular!)

  • Each Spatial needs its own instance of the Control.

  • An AbstractControl has a reference to its attached spatial. Other dependencies can be passed in explicitly; keep scene-graph changes on the application thread.

  • Controls can be saved as .j3o file together with a Spatial.

Examples: You can write

  • A WalkerNavControl, SwimmerNavControl, FlyerNavControl… that defines how a type of NPC finds their way around. All NPCs can walk, some can fly, others can swim, and some can all three, etc.

  • A PlayerNavControl that is steered by user-configurable keyboard and mouse input.

  • A generic animation control that acts as a common interface that triggers animations (walk, stand, attack, defend) for various entities.

  • A DefensiveBehaviourControl that remote-controls NPC behaviour in fight situations.

  • An IdleBehaviourControl that remote-controls NPC behaviour in neutral situations.

  • A DestructionControl that automatically replaces a structure with an appropriate piece of debris after collision with a projectile…

The possibilities are endless. smile

Example Code

Other examples include the built-in RigidBodyControl in JME’s physics integration, the built-in TerrainLODControl that updates the terrain’s level of detail depending on the viewer’s perspective, etc.

Existing examples in the code base include:

  • AnimComposer.java plays animation actions and supports layers.

  • CameraControl.java allows you to sync the camera position with the position of a given spatial.

  • BillboardControl.java displays a flat picture orthogonally, e.g. a speech bubble or informational dialog.

  • PhysicsControl subclasses (such as CharacterControl, RigidBodyControl, VehicleControl) allow you to add physical properties to any spatial. PhysicsControls tie into capabilities provided by the BulletAppState.

AbstractControl Class

Tip

The most common way to create a Control is to create a class that extends AbstractControl.

The AbstractControl can be found under com.jme3.scene.control.AbstractControl. This is a default abstract class that implements the Control interface.

  • You have access to a boolean isEnabled().

  • You have access to the Spatial object spatial.

  • You override the controlUpdate() method to implement the Spatial’s behaviour.

  • You have access to a setEnabled(boolean) method. This activates or deactivates this Control’s behaviour in this spatial temporarily. While the AbstractControl is toggled to be disabled, the controlUpdate() loop is no longer executed.

For example, you disable your IdleBehaviourControl when you enable your DefensiveBehaviourControl in a spatial.

A subclass implements controlUpdate() and controlRender(). Override setSpatial() only when attachment or removal needs extra work, and call the superclass implementation. For serialized fields, implement read() and write():

public class MyControl extends AbstractControl {
    private int index;

    public MyControl() {} // for serialization

    public MyControl(int index) {
        this.index = index;
    }

    @Override
    protected void controlUpdate(float tpf) {
        if (spatial != null) {
            spatial.rotate(0, tpf, 0);
        }
    }

    @Override
    protected void controlRender(RenderManager rm, ViewPort vp) {
        // Optional render-time work.
    }

    @Override
    public void write(JmeExporter ex) throws IOException {
        super.write(ex);
        ex.getCapsule(this).write(index, "index", 0);
    }

    @Override
    public void read(JmeImporter im) throws IOException {
        super.read(im);
        index = im.getCapsule(this).readInt("index", 0);
    }
}

The snippet uses engine types and java.io.IOException; add their imports in your project. AbstractControl implements JmeCloneable. For custom mutable references, override cloneFields() and clone them with the provided Cloner as appropriate; copying a primitive field such as index does not require that. Test both cloning and serialization when your control owns additional state.

See also:

  • To learn more about write() and read(), see Save and Load

  • To learn more about setUserData(), see Spatial.

The Control Interface

Control extends Savable and declares setSpatial, update, and render, as well as the legacy cloneForSpatial method. cloneForSpatial is deprecated; use the engine's JmeCloneable cloning protocol when implementing a cloneable control. Serialization and cloning are separate operations.

setEnabled() and isEnabled() are features of AbstractControl, not methods required by Control itself. If you implement Control directly, provide the declared lifecycle and serialization methods, manage any enabled flag yourself, and define cloning behavior appropriate to the class. Most controls can extend AbstractControl instead.

You can define a more specific interface extending Control when different implementations need to expose a common API:

public interface ManualControl extends Control {
    void steerX(float value);
    void moveY(float value);
}

An implementation can extend AbstractControl and implement ManualControl. Attach a separate control instance to each spatial, then use getControl(ManualControl.class) and check for null when that control may be absent.

Best Practices

Use the getControl() accessor to get Control objects from Spatials. No need to pass around lots of object references. Here’s an example from the MonkeyZone code:

public class CharacterAnimControl implements Control {
    ...
    public void setSpatial(Spatial spatial) {
        ...
        animComposer     = spatial.getControl(AnimComposer.class);
        characterControl = spatial.getControl(CharacterControl.class);
        ...
    }
}

You can create custom Control interfaces so a set of different Controls provide the same methods and can be accessed with the interface class type.

public interface ManualControl extends Control {
    public void steerX(float value);
    public void steerY(float value);
    public void moveX(float value);
    public void moveY(float value);
    public void moveZ(float value);
    ...
}

Then you create custom sub-Controls and implement the methods accordingly to the context:

public class ManualVehicleControl extends AbstractControl implements ManualControl {...}

and

public class ManualCharacterControl extends AbstractControl implements ManualControl {...}

Then add the appropriate controls to spatials:

characterSpatial.addControl(new ManualCharacterControl());
...
vehicleSpatial.addControl(new ManualVehicleControl());
...

Tip

Use the getControl() method on a Spatial to get a specific Control object, and activate its behaviour!

ManualControl c = mySpatial.getControl(ManualControl.class);
if (c != null) {
    c.steerX(steerX);
}