CS 269/369: TorqueScript Tutorial 1

TorqueScriptTutorial 1


This tutorial is intended to familiarize you with TorqueScript, the scripting language for all Torque game engines. It assumes some familiarity with C/C++, on which TorqueScript is modeled syntactically.

  1. Start up Torque Game Builder (TGB).
  2. Create a new project, save the project on your network directory.
  3. Once in your project, create a new Scene/level by clicking on the disk icon and naming the level in the resulting Save As... dialog. Levels should be saved in the game/data/levels subdirectory relative to the project file.
  4. In the gameScripts directory, create a script file called test.cs and open it in a text editor. This is where we will write the TorqueScript (TS).
  5. In the test.cs file, create a function test1
    function test1() {
      echo("Hello world");
      echo("2 + 2 is: ", 2 + 2 );
    }
    
  6. Run the game in TGB by clicking on the play icon. Bring up the console window in the game by typing ~.
  7. After you bring up the console window, take a look at what it says. The content of the console is similar to a linux startup screen. It tells you about the processor, initializes various packages, and then starts compiling and loading scripts.

    Note that the first script it initializes, by default, is main.cs. The main.cs script controls what other scripts the game engine loads on startup.

    After compiling a set of scripts, the engine provides more information about the graphics card and its capabilities. Then it compiles and loads more scripts, including the GUI scripts and the level sript.

    It is important to look at the startup console when you run your own scripts because that is where you will see syntax errors or other problems with your code. The game will still start if your code does not compile, it will just use an older version of your code, or no version at all. The only way to see a syntax error is on the console startup window.

  8. Load and compile the script file using the exec() function in the console window.
    exec("./game/gameScripts/test.cs");
    
  9. To run functions from scripts just type the name of the function. Now type test1(); in the debugging window and hit return.
  10. Let's do some more scripts that explore variables and control flow. Put the following function into test.cs.
    function test2() {
      if( $gbl_a == 1 ) {
        echo("gbl_a is 1");
      }
      else {
        echo("gbl_a is not 1");
      }
    }
    

    Note that we're using the variable $gbl_a in the script above. Variables that begin with a $ are global variables. Variables that begin with a % are local variables and are destroyed when their scope (function block) terminates.

  11. We could run the game engine and load test.cs manually each time, but if we are writing scripts we want to use in the game engine, we need to tell the game engine to load them automatically. The place to do this is in the main.cs script file in the game subdirectory (not the main.cs in the same directory as the project.t2dProj file). Edit the file and put the following line after the exec call to game.cs.
    exec("./gameScripts/test.cs");
    

    Now when you run the game, test.cs will automatically load and be compiled.

  12. Run the game, open the console (~ key), and assign a value to the global variable $gbl_a. Assigning a value to any variable (local or global) creates that variable, just like in Python. Like Python, variables in TS are not typed and can hold any kind of data.
    $gbl_a = 5;
    

    Since we are using a $ symbol before the variable name, this variable has global scope and is persistent once we've created it. Now run the function test2(). Try changing the value of $gbl_a to 1 and running test2() again.

  13. As noted, variables in TS have no type. Variables in TS are also not case sensitive. Let's do some quick string manipulation with variables. Assign strings to two variables $a and $b.
    $a = "Thing 1";
    $b = "Thing 2";
    

    You can print out these strings using the echo function. There are a number of ways to concatenate strings together. The concatenation operators are the symbols: @, TAB, SPC, and NL. Print out the strings using each of these symbols in between and see what happens. For example...

    echo( $a SPC $b );
    
  14. Arrays in TS are a bit more interesting. The typical method of creating and indexing one-dimensional arrays is to use square brackets, just like C.
    $a[0] = 1;
    $a[1] = 2;
    

    Just for kicks, now try printing out $a and $a[0]. Note that they refer to different memory locations. Again, just for kicks, try printing out $a0 and $a1. Note that $a[0] and $a0 both refer to the same thing. When reading variable names, the interpreter removes the left bracket, so you have to be careful about terminating regular variable names with numbers.

    Undefined variables have a null value, but using an undefined variable does not cause an error. For example, try the expression:

    echo( $a[0] + $q );
    
  15. The strange way of indexing variable names, however, makes it possible to do some interesting things with strings. In particular, you can create variable names on the fly and effectively index into an array using strings, similar to a dictionary in Python.
    $coolBeans = "A";
    $coolHand = "B";
    $coolBreeze = "C";
    echo($cool["Beans"]);
    echo($cool["Hand"]);
    echo($cool["Breeze"]);
    

    You can also create a variable to hold the string to use as the index, meaning you can dynamically index an array using a strings.

  16. 2-dimensional arrays in Torquescript use commas inside the square brackets.
    $a[0, 0] = 42;
    

    As before, the location $a[0, 0] is different from $a[0] and $a. The TS interpreter substitutes an underscore for a comma in a multi-dimensional array, so the name $a0_0 also refers to $a[0, 0].

  17. When comparing numeric values, use the == operator. When comparing strings, you want to use the $= operator, which compares the values of the strings. Note that the comparison 0 == "" will return true, but the comparison 0 $= "" will return false.
  18. TS includes the standard C control structures: if, switch, for, and while. Try incorporating some of them into test2() using some global and local variables. For example:
    function test3() {
      %agent = 5;
      %action = 2;
    
      if( %a == 5 ) {
        switch( %action ) {
        case 0:
          echo( "action 0" );
        case 1:
          echo( "action 1" );
        case 2:
          echo( "action 2" );
        default:
          echo( "do nothing" );
        }
      }
    
      for(%i = 0;%i < 3;%i++) {
        echo("doing action: ", %action );
      }
    
      while(%i > 0) {
        echo( "response " );
        %i--;
      }
    }
    
  19. Functions in TS begin with the function keyword. Functions do not have specified return types. A function returns whatever is provided in the return statement (or NULL if no return value is provided).

    TS supports recursion, so be careful.

  20. Add the puzzle art resource to your test project (Project menu).
  21. Now let's write a function to create a new sprite in the game window, which shows us how to create new objects. The type of object we want to create is called a t2dStaticSprite, which is basically an image that becomes an object within the game engine. Note that we'll store the object in the global variable $gem so we can refer to it in the console window.
    function test3( %scenegraph ) {
    
      // create a new t2dStaticSprite object with some default field values
      $gem = new t2dStaticSprite() {
        imageMap = "puzzleGem_7ImageMap";
        frame = "0";
        canSaveDynamicFields = "1";
        Position = "10 0";
        size = "7 7";
        mountID = "3";
      };
    
      // add the sprite to the scene graph
      %scenegraph.addToScene($gem);
    
      // start the gem rotating slowly
      $gem.setAngularVelocity( 10.0 );
    
    }
    

    Save the file, start up the game engine, and then call test3() with the argument $lastLoadedScene, which is the last scenegraph loaded into the game engine.

    test3($lastLoadedScene);
    

    The gem should appear in the image, rotating slowly. You can change the orientation of the image using the method setRotation.

    $gem.setRotation("45");
    

    You can see all of the fields of the object $gem as well as all of the methods it possesses by typing.

    $gem.dump();
    
  22. Mess around a little and see what else you can do with the gem. Try things like setLinearVelocityX, setLinearVelocityY, and setAngularVelocity. Note that the screen does not wrap by default, so you can send the gem out to infinity.

At this point, you have written some functions in torquescript, created an object, manipulated it, and figured out how to print out stuff on the debugging console. All of these are incredibly important skills going forward. Next, it's time to learn how the TGB GUI works.