- jMonkeyEngine 3.0 Beginner’s Guide
- Ruth Kusterer
- 337字
- 2025-04-04 22:38:53
Time for action – call me maybe?
In the CubeChaser
class, the added CubeChaserControl
classes mark individual cubes, and the AppState
object identifies and transforms them when certain conditions are met. Combining both AppState
objects and controls can be quite powerful! You often use AppState
objects to work with certain subsets of spatials that all carry one specific control.
A control can add custom methods to its spatial, and the AppState
object can call these methods to make individual spatials do the AppState
object's bidding. As an example, let's make the scared cubes identify themselves by name, and count how often cubes get scared in total.
- Add the following custom method to the
CubeChaserControl
class:public String hello(){ return "Hello, my name is "+spatial.getName(); }
- In the
CubeChaserState
class, create a simple counter variable and a public accessor for it.private int counter=0; public int getCounter() { return counter; }
- In the
CubeChaserState
class, call thehello()
method on eachtarget
that you want to interact with. Place the following call after thetarget.move(…)
line in theupdate()
method:System.out.println( target.getControl(CubeChaserControl.class).hello() + " and I am running away from " + cam.getLocation() ); counter++;
- In the
simpleUpdate()
method of theCubeChaser
class, add the following call to get some status information about the runningAppState
method:System.out.println("Chase counter: " + stateManager.getState(CubeChaserState.class). getCounter());
When you run the CubeChaser
class now and chase a cube, you see console output such as the Hello, my name is Cube12 and I am running away from (-17, -13, 1) message, together with a count of how often the AppState
object has moved any cubes away.
What just happened?
Just like a spatial has a spatial.getControl()
method to let neighboring controls communicate with it, an SimpleApplication
class has a stateManager
.getState()
method to access neighboring AppState
objects in the same appManager
class. For example, you can call the AppStates.getCounter()
method of the CubeChaserState from every place where you have access to the central stateManager
, as shown next:
int x = stateManager.getState(CubeChaserState.class).getCounter();