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

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();
主站蜘蛛池模板: 巴彦县| 梅州市| 英吉沙县| 禄丰县| 家居| 科技| 门头沟区| 南郑县| 那坡县| 宜宾县| 石屏县| 惠水县| 眉山市| 修武县| 郑州市| 云和县| 郑州市| 左权县| 阜平县| 灵台县| 平凉市| 台山市| 丽水市| 张北县| 平安县| 广德县| 新化县| 乐东| 中方县| 合作市| 庆元县| 桂平市| 申扎县| 嘉禾县| 昌平区| 洪江市| 德格县| 景东| 利川市| 夏河县| 故城县|