Scripting Game Objects

Part 1

Before we look at how to script game objects in detail, it is worth seeing it in action. This video shows one of the examples that is shipped with the library and is worth watching to set the rest of this and the next guide in context.

 

Overview of how it was done

In this example three new methods were created to control the helicopter - reset, move and turn. It was also necessary to create 3 new events, one for each method. The way they were created is essentially the same as you saw in the previous guides.

There is one significant issue to address and that is how to get QScript to recognise the game object as a variable that can be used in the script.

The answer is the Thing class, which is used to wrap your game object into a special type of variable that QScript can work with. You will see how to do this in the next guide but for the moment lets see how it is used in our user defined method - reset.

public static class ResetFunction extends Operator {

  public ResetFunction(String symbol, int nbrArgs, int priority, int type) {
    super(symbol, nbrArgs, priority, type);
  }
  
  public Argument resolve(Script script, Token token, Argument[] args, Object... objects)
  throws EvaluationException {
    testForUninitialisedVars(script, args);
    Argument a0 = args[0]; // Helicopter wrapped up in a thing object
    Argument a1 = args[1]; // x position
    Argument a2 = args[2]; // y position
    Argument a3 = args[3]; // angle
    if (a0.isThing() && a1.isNumeric() && a2.isNumeric() && a3.isNumeric()) {
      Float px = a1.toFloat_();
      Float py = a2.toFloat_();
      Float ang = a3.toFloat_();
      script.fireEvent(ResetEvent.class, null, a0, new Object[] { a0.getValue(), px, py, ang } );
      // Wait until told by the user to resume
      script.waitFor(0);
      return null;
    }

    // If we get here then the arguments are invalid
    handleInvalidArguments(script, token);
    return null;
  }
}

This method has 4 parameters and these are retrieved in lines 10-13 inclusive. The first parameter is our helicopter object (wrapped in a Thing object) the other 3 should all be numeric and this is tested in line 14.

Provided the data types are correct a ResetEvent event is fired in line 18. The last parameter is an Object array containing the values of the parameters so they can be used in the main sketch.

Line 19 is important because it pauses the script until the main program has proccessed the event and finished the action

In the next guide we look at the Helicopter class in great details.