Putting It All Together

A BeanShell script to demonstrate delayed tasks is in Listing 14.14. In this script, when the player touches the stairTrigger, the switch begins to move; the stairs begin to move up after 750ms. After five seconds, the closeStairs() method is called to bring the stairway down to the floor.

Listing 14.14 Moving Stairs in level1.bsh
 Functions to open and close a stairway.
global.stairsOn = false;
player_stairTriggerTouch() {
 if (global.stairsOn) {
openStairs() {
 // swing the switch ("turret") to the "on" position
 group = stairTrigger.getPolygonGroup().getGroup("turret");
 group.getTransform().turnYTo(3.14159f, 0.005f);
 // move the stairs up after 750 ms
 delay(750, "toggleStairs(true)");
 delay(5000, "closeStairs()");
 global.stairsOn = true;
closeStairs() {
 // swing the switch ("turret") to the "off" position
 group = stairTrigger.getPolygonGroup().getGroup("turret");
 group.getTransform().turnYTo(0, 0.005f);
 // move the stairs down
 delay(750, "global.stairsOn = false;");
toggleStairs(boolean raise) {
 moveYTo(stair1, raise?192:0, .1f);
 moveYTo(stair2, raise?192:0, .1f);
 moveYTo(stair3, raise?192:0, .1f);
 moveYTo(stair4, raise?192:0, .1f);
 moveYTo(stair5, raise?192:0, .1f);
 moveYTo(stair6, raise?128:0, .1f);
 moveYTo(stair7, raise?64:0, .1f);

As a demonstration, the code for this chapter in the tutorial includes the EventTest class, which uses the 3D engine in this tutorial and combines it with scripting and delayed tasks. The only update this class needs over previous chapters is setting up the script manager and updating the game task manager every frame. To run this test, you need to include the BeanShell library in your classpath. You can use the run task in the Ant build file included with the source, or you can run the test from the command line from the build folder, like this:

java -cp ..\lib\bsh-core-1.2b7.jar;. EventTest

A screenshot of the demo is in Screenshot.

Screenshot This screenshot of this chapter's demo shows a door opening (the bars) and a switch in the background. The switch activates a staircase.

Java graphics 14fig04.gif

Remember, part of the fun of making environment interaction like this is letting the player discover what happens. Be sure to occasionally make your environment interaction unique and not obvious. Occasionally let the players explore around a little and find things on their own.