Studio Wikiv0.8.7

Wiki / Gameplay

Add a Java Behaviour

Create a project-registered script, handle a keypad press, and build it into a MIDlet.

Create and attach a script

Start with the cube in a new scene. Select it in the Hierarchy and choose Add Component… → Java Behaviour in its Inspector. Name the class StepRight. Open the new Java file from Assets, replace its contents with the example, and save. Studio registers the script and attaches it to the cube. Lowercase names such as test work too. For an existing script, drag its tile from Assets onto a mesh or group in the Hierarchy, onto a mesh in the Scene view, or into the selected object’s Inspector. You can attach several scripts, including multiple instances of the same class. Each instance has its own public field overrides.

Java source must have a package declaration, a public class whose name matches the filename, and a public no-argument constructor (or no explicit constructor). The example below is the complete source for assets/StepRight.java. It implements the actual SceneBehaviour callback and uses getNode() to move its attached M3G node.

java
package game;

import dev.j2me.runtime.SceneBehaviour;
import javax.microedition.lcdui.Canvas;

public final class StepRight extends SceneBehaviour {
    protected boolean onKeyPressed(int keyCode, int action) {
        if (keyCode != Canvas.KEY_NUM6) return false;
        getNode().translate(1.0f, 0.0f, 0.0f);
        return true;
    }
}

Build the script

The build compiles registered scripts with the project and the Java ME APIs. The game.StepRight name comes from the package game; line and public class declaration. Each Behaviour instance refers to the registered script by scriptId. Studio stores multiple instances in the object’s ordered behaviours array in scene version 18. Existing single behaviour entries still load. Studio adds that registration and component when you create the script from the selected object's workflow; if assembling project data by hand, both references must be present.

The base class callbacks are onStart, onUpdate(int deltaMillis), onPause, onResume, onKeyPressed(int keyCode, int action), and onKeyReleased(int keyCode, int action). For scenes with an enabled Java Behaviour, Play builds and runs the MIDlet inside the Game view. Test MIDlet launches it in the separate emulator window.

Save the scene and press Test MIDlet. Tap Numpad 6 once. The cube should jump one unit to the right. Change 1.0f to 0.25f, save, and rebuild to try a smaller step.