Game Development Reference
In-Depth Information
How to do it...
To attach an input
AppState
object, perform the following steps:
1. Start off by creating a class called
InputAppState
, extending
AbstractAp-
pState
, and implementing
ActionListener
and
AnalogListener
.
2. The
InputAppState
class needs a couple of fields to be functional. First of all,
we're going to keep a reference to the application's
InputManager
in a field
called
inputManager
. We're also adding a
GameCharacterControl
field
called
character
. This can be replaced by any
spatial
. Lastly, we're going to
have a value that controls the sensitivity of the analog controls. We do this with a
float called sensitivity. Add getters and setters for character and sensitivity.
3. Next, we'll set up the kinds of input we're going to handle. Strings are used by
jMonkeyEngine for the mappings, but enums can be easier to manage across
classes. Here, we'll use an
enum
and supply the name of the value as the mapping.
We use it to create some basic FPS controls as follows:
public enum InputMapping{
RotateLeft, RotateRight, LookUp, LookDown,
StrafeLeft,
StrafeRight, MoveForward, MoveBackward;
}
4. We create a method called
addInputMappings
to add these to
inputMan-
ager
and make sure it listens to them. To do this, we supply the name of the
enum
value as the mapping and bind it to a certain input as follows:
private void addInputMappings(){
inputManager.addMapping(InputMapping.RotateLeft.name(),
new MouseAxisTrigger(MouseInput.AXIS_X, true));
inputManager.addMapping(InputMapping.RotateRight.name(),
new MouseAxisTrigger(MouseInput.AXIS_X, false));
inputManager.addMapping(InputMapping.LookUp.name(),
new MouseAxisTrigger(MouseInput.AXIS_Y, false));
inputManager.addMapping(InputMapping.LookDown.name(),
new MouseAxisTrigger(MouseInput.AXIS_Y, true));