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.

  1. Add the following custom method to the CubeChaserControl class:
    public String hello(){
            return "Hello, my name is "+spatial.getName();
    }
  2. In the CubeChaserState class, create a simple counter variable and a public accessor for it.
    private int counter=0; 
    public int getCounter() { return counter; }
  3. In the CubeChaserState class, call the hello() method on each target that you want to interact with. Place the following call after the target.move(…) line in the update() method:
    System.out.println(
        target.getControl(CubeChaserControl.class).hello()
        + " and I am running away from " + cam.getLocation() );
    counter++;
  4. In the simpleUpdate() method of the CubeChaser class, add the following call to get some status information about the running AppState 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();