- jMonkeyEngine 3.0 Beginner’s Guide
- Ruth Kusterer
- 401字
- 2025-04-04 22:38:53
Time for action – pushing the right buttons
Remember our friend, the blue cube from the template? Let's write some code that changes the cube state: the cube has a color, a scale, a location, and a rotation. So just for fun, let's make the cube rotate when we left-click on it, and change its color every time we press the Space bar.
- Make another copy of the
BasicGame
project'sMain.java
template and name the classUserInput.java
. Remember to also refactor the first line of themain()
method to the following:UserInput app = new UserInput();.
- Define class constants that represent the Space bar and left-click of the mouse. Import the necessary classes from the
com.jme3.input.*
andcom.jme3.input.controls.*
packages.private final static Trigger TRIGGER_COLOR = new KeyTrigger(KeyInput.KEY_SPACE); private final static Trigger TRIGGER_ROTATE = new MouseButtonTrigger(MouseInput.BUTTON_LEFT);
- Define two String class constants. We use these Strings to identify the two actions later: rotating the cube and toggling its color.
private final static String MAPPING_COLOR = "Toggle Color"; private final static String MAPPING_ROTATE = "Rotate";
Tip
In the jMonkeyEngine SDK, place the insertion point behind the period after KeyInput.
or MouseInput.
, and so on. Then press Ctrl + Space bar to select constants from the code-completion pop-up. You also find a list of input triggers for mouse, keyboard, touch, and joystick events in the appendix.
You now have two triggers, TRIGGER_COLOR
and TRIGGER_ROTATE
, and two mappings, MAPPING_COLOR
and MAPPING_ROTATE
.
What just happened?
Each physical input, such as the Space bar or left-click of the mouse , is represented by a Trigger
object. You create a KeyTrigger
object for a key. You create MouseButtonTrigger
objects for mouse clicks, and MouseAxisTrigger
objects for mouse movement. Similarly, you create JoyAxisTrigger
objects and JoyButtonTrigger
objects for joystick buttons and movements. Android devices also support TouchTrigger
objects that act similarly to MouseButtonTrigger
objects.
The two action names that you prepared here, MAPPING_COLOR
and MAPPING_ROTATE
, are mappings. The mappings are case-sensitive Strings, and must be unique, one for each action. For mappings, always choose meaningful names that reflect the action, not the trigger. This way they still make sense even if you change the assigned triggers later.
Using String constants instead of Strings has the advantage that the compiler warns you if you misspell the mapping (as opposed to silently ignoring your input). Using String constants also makes it possible to use IDE features, such as refactoring or finding usages.