官术网_书友最值得收藏!

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.

  1. Make another copy of the BasicGame project's Main.java template and name the class UserInput.java. Remember to also refactor the first line of the main() method to the following:
    UserInput app = new UserInput();.
  2. Define class constants that represent the Space bar and left-click of the mouse. Import the necessary classes from the com.jme3.input.* and com.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);
  3. 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.

主站蜘蛛池模板: 聂拉木县| 清水河县| 衢州市| 桐梓县| 长葛市| 德化县| 孟连| 眉山市| 来宾市| 南昌县| 东辽县| 云龙县| 黑龙江省| 天津市| 曲水县| 合山市| 靖州| 淮滨县| 迁安市| 恩施市| 容城县| 衡东县| 修武县| 丹寨县| 维西| 长治县| 吕梁市| 嘉善县| 连城县| 自贡市| 蓬安县| 和田市| 辽宁省| 株洲县| 海阳市| 招远市| 同江市| 定陶县| 菏泽市| 白山市| 游戏|