Skip to content

RTSPrototype

LuisAntonRebollo edited this page Dec 4, 2013 · 1 revision
<SCRIPT SRC="../../../include/tutorial.js" LANGUAGE="JavaScript"></SCRIPT> <SCRIPT SRC="../../../include/prototype.js" LANGUAGE="JavaScript"></SCRIPT> <SCRIPT SRC="../../../include/scriptaculous.js" LANGUAGE="JavaScript"></SCRIPT> <SCRIPT SRC="../../../include/glossaryLookUp.js" LANGUAGE="JavaScript"></SCRIPT> <SCRIPT SRC="../../../include/referenceLookUp.js" LANGUAGE="JavaScript"></SCRIPT> <SCRIPT SRC="../../../include/component.js" LANGUAGE="JavaScript"></SCRIPT> <SCRIPT SRC="../../../include/componentContainer.js" LANGUAGE="JavaScript"></SCRIPT> <SCRIPT>DocImagePath = "../../../";</SCRIPT> <script> // this script chunk is to update the ToC to the current doc and expand it pageID = 57; parent.leftFrame.expandToItem('tree2', 'doc57'); var element = parent.leftFrame.document.getElementById('doc57'); if((element) && (element.className==parent.leftFrame.nodeClosedClass)) { element.className = parent.leftFrame.nodeOpenClass } ; </script> <title>Torque3D - RTS Prototype</title>
    <table border="0" cellpadding="15" cellspacing="0" width="700">
      <tbody>
        <tr>
          <td width="700"><table id="toc" summary="Contents">
              <tbody>
                <tr>
                  <td><div id="toctitle">
                      <h2>Contents</h2>
                    <ul>
                      <li class="toclevel-1"><a href="#Introduction"><span class="tocnumber">1</span> <span class="toctext">Introduction</span></a></li>
                      <li class="toclevel-1"><a href="#Create_Project"><span class="tocnumber">2</span> <span class="toctext">Create A New Project</span></a></li>
                      <li class="toclevel-1"><a href="#Camera_Setup"><span class="tocnumber">3</span> <span class="toctext">Camera Setup</span></a></li>
                      <li class="toclevel-1"><a href="#Mouse_Setup"><span class="tocnumber">4</span> <span class="toctext">Mouse Setup</span></a>
                        <ul>
                          <li class="toclevel-2"><a href="#Mouse_Cursor_Toggling"><span class="tocnumber">4.1</span> <span class="toctext">Mouse Cursor Toggling</span></a></li>
                          <li class="toclevel-2"><a href="#Mouse_Click_Reaction"><span class="tocnumber">4.2</span> <span class="toctext">Placing Structures Using The GUI</span></a></li>
                        </ul>
                      </li>
                      <li class="toclevel-1"><a href="#Mouse-Driven_Input"><span class="tocnumber">5</span> <span class="toctext">Mouse-Driven Input</span></a>
                        <ul>
                          <li class="toclevel-2"><a href="#Player_Spawning"><span class="tocnumber">5.1</span> <span class="toctext">Player Spawning</span></a></li>
                          <li class="toclevel-2"><a href="#Movement"><span class="tocnumber">5.2</span> <span class="toctext">Movement</span></a></li>
                          <li class="toclevel-2"><a href="#Spawning_Enemy_Targets"><span class="tocnumber">5.3</span> <span class="toctext">Spawning Enemy Targets</span></a></li>
                          <li class="toclevel-2"><a href="#Attacking"><span class="tocnumber">5.4</span> <span class="toctext">Attacking</span></a></li>
                          <li class="toclevel-2"><a href="#Tweaking_Attacks"><span class="tocnumber">5.5</span> <span class="toctext">Tweaking Attacks</span></a></li>
                        </ul>
                      </li>
                      <li class="toclevel-1"><a href="#Destination_Markers"><span class="tocnumber">6</span> <span class="toctext">Destination Markers</span></a>
                        <ul>
                          <li class="toclevel-2"><a href="#Creating_a_Material"><span class="tocnumber">6.1</span> <span class="toctext">Creating a Material</span></a></li>
                          <li class="toclevel-2"><a href="#Creating_a_Decal"><span class="tocnumber">6.2</span> <span class="toctext">Creating a Decal</span></a></li>
                          <li class="toclevel-2"><a href="#Spawning_the_Marker"><span class="tocnumber">6.3</span> <span class="toctext">Spawning the Marker</span></a></li>
                          <li class="toclevel-2"><a href="#Erasing_the_Marker"><span class="tocnumber">6.4</span> <span class="toctext">Erasing the Marker</span></a></li>
                        </ul>
                      </li>
                      <li class="toclevel-1"><a href="#Camera_Modes"><span class="tocnumber">7</span> <span class="toctext">Camera Modes</span></a>
                        <ul>
                          <li class="toclevel-2"><a href="#Orbit_Camera"><span class="tocnumber">7.1</span> <span class="toctext">Orbit Camera</span></a></li>
                          <li class="toclevel-2"><a href="#Overhead_Camera"><span class="tocnumber">7.2</span> <span class="toctext">Overhead Camera</span></a></li>
                        </ul>
                      </li>
                      <li class="toclevel-1"><a href="#GoingRTS"><span class="tocnumber">8</span> <span class="toctext">Going More Real-Time Strategy</span></a></li>
                      <li class="toclevel-1"><a href="#Conclusion"><span class="tocnumber">9</span> <span class="toctext">Conclusion</span></a></li>
                    </ul></td>
                </tr>
              </tbody>
            </table>
            <a name="Introduction" id="Introduction"></a>
            <h2> <span class="mw-headline">Introduction</span></h2>
            <p>Torque 3D's stock demos and templates are setup for first person
              shooter (FPS) games. However, the engine has multiple camera modes that
              can change the perspective and how the game is controlled. In this
              tutorial, we are going to modify the camera and mouse controls to
              emulate different game types: Hack &amp; Slash and RTS. </p>
            <p>Some of the topics that will be covered are: </p>
            <ul>
              <li>Advanced scripting </li>
              <li>Camera manipulation </li>
              <li>Simple AI </li>
              <li>Object spawning </li>
              <li>Mouse and keyboard input </li>
              <li>Basic RTS and Hack &amp; Slash mechanics </li>
            </ul>
            <p><br />
              Before you begin, you should be familiar with the following guides. Make sure you have read these before proceeding: </p><br />
            <ul>
              <li>TorqueScript Syntax </li>
              <li>Camera Modes </li>
              <li>World Editor Interface </li>
              <li>Adding 3D Shapes </li>
              <li>Material Editor </li>
              <li>Decal Editor </li>
              <li>Datablock Editor </li>
            </ul>
            <a name="Create_Project" id="A2"></a>
            <h2> <span class="mw-headline">Create A Fresh Project</span></h2>
            <p>We&#39;re going to start with a clean project, so open the Toolbox and create one 
                using the Full Template.&nbsp; This will give us a blank terrain to work with.</p>
              <p><br />
                  <img alt="" src="images/MTNewProject.png" /></p>
              <p>Name your new project RTS_Prototype and select the Full template.</p>
              <p><br />
                  <img alt="" src="images/RTS_CreateNewProject.png" /></p>
              <p>When the project has been created, select your project (1), select the <strong>
                  Empty Terrain</strong> mission (2) and open it in the World Editor (3).</p>
              <p><br />
                  <img alt="" src="images/RTS_SelectAndEditProject.png" /></p>
            <p><br />
              The Full Template used for this tutorial project should contain base art and scripts needed to run the game, but we want to use some custom models. Start by <a href="rts_prototype_art.zip" class="downloads">CLICKING HERE</a> to download a zip file containing the sample assets.</p>

            <p><br />
                Copy the art folder in the zip file on top of your project's art file. This will add the models, their datablocks, and their materials to your project if they do not exist. When you are ready, continue reading to configure your mouse controls. 
            </p>
            <p><br />
                <img alt="" src="images/RTS_FileLocations.png" />
            </p>
            <p><br />
                <strong>BoomBot.cs</strong>, which contains the&nbsp; should be located in the 
                <strong>game/art/datablocks</strong> folder (1).&nbsp; The image for the 
                building placement button should be in the <strong>game/art/gui</strong> folder 
                (2).&nbsp; The files associated with Boom Bot's model, textures and animations should be located in the
                <strong>game/art/shapes/actors/BoomBot</strong> folder (3).
            </p>
            <p><br />
                The zip file adds two new models to the project. One is a simple, static building. The other is a custom player model called Boom Bot. While you can simply drag and drop these models in via the World Editor, we need to hook up a script file prepared specifically for Boom Bot.</p>
            <p><br />
                To get Boom Bot fully working, open <b>game/art/datablocks/datablockExec.cs</b> Scroll down until you see the following code:</p>
            <br />
            <pre>exec("./aiPlayer.cs");</pre>
            <br />
            <p>Just below that line, add the following:</p>
            <br />
            <pre>exec("./BoomBot.cs");</pre>
            <p><br />
                In Torsion it should look something like this:
            </p>
            <p><br /><img alt="" src="images/RTS_AddBoombotExec.png" /></p>
            <p>Also, check your BoomBot datablock if you are not using the files from the download.  It should look like this:</p>
            <br />
            <pre>

datablock PlayerData(BoomBotData : DefaultPlayerData) { shapeFile = "art/shapes/actors/BoomBot/BoomBot.dts";

boundingBox = "1.1 1.2 2.5"; pickupRadius = "1.2"; };

Next, in scripts/server/gameDM.cs we'll change the default player class and datablock.  In DeathMatchGame::initGameVars() make the following changes:

    $Game::defaultPlayerClass = "AiPlayer";
    $Game::defaultPlayerDataBlock = "BoomBotData";

This gives us the ability to tell our unit where to go and let the AI class handle getting it there. It also lets us have our default player be the BoomBot without having to specify it at the spawnpoint.


Camera Setup

First we're going to set up our camera mode framework. In scripts/server/commands.cs we're going to add some functions to set and toggle our camera modes. The following code can sit at the end of the script file:

// ----------------------------------------------------------------------------
// Camera commands
// ----------------------------------------------------------------------------

function serverCmdorbitCam(%client) { %client.camera.setOrbitObject(%client.player, mDegToRad(20) @ "0 0", 0, 5.5, 5.5); %client.camera.camDist = 5.5; %client.camera.controlMode = "OrbitObject"; } function serverCmdoverheadCam(%client) { %client.camera.position = VectorAdd(%client.player.position, "0 0 30"); %client.camera.lookAt(%client.player.position); %client.camera.controlMode = "Overhead"; }

function serverCmdtoggleCamMode(%client) { if(%client.camera.controlMode $= "Overhead") { %client.camera.setOrbitObject(%client.player, mDegToRad(20) @ "0 0", 0, 5.5, 5.5); %client.camera.camDist = 5.5; %client.camera.controlMode = "OrbitObject"; } else if(%client.camera.controlMode $= "OrbitObject") { %client.camera.controlMode = "Overhead"; %client.camera.position = VectorAdd(%client.player.position, "0 0 30"); %client.camera.lookAt(%client.player.position); } }

function serverCmdadjustCamera(%client, %adjustment) { if(%client.camera.controlMode $= "OrbitObject") { if(%adjustment == 1) %n = %client.camera.camDist + 0.5; else %n = %client.camera.camDist - 0.5;

  if(%n < 0.5)
     %n = 0.5;
     
  if(%n > 15)
     %n = 15.0;
     
  %client.camera.setOrbitObject(%client.player, %client.camera.getRotation(), 
    0, %n, %n);
  %client.camera.camDist = %n;

} if(%client.camera.controlMode $= "Overhead") { %client.camera.position = VectorAdd(%client.camera.position, "0 0 " @ %adjustment); } }

Additionally, in scripts/client/default.bind.cs we'll add some keybinds and utility functions to assist in controlling the camera:

function toggleCameraMode(%val)
{
   if (%val)
      commandToServer('toggleCamMode');
}

moveMap.bind( keyboard, "ctrl m", toggleCameraMode);

function mouseZoom(%val) { if(%val > 0) { commandToServer('adjustCamera', -1); } else { commandToServer('adjustCamera', 1); } }

moveMap.bind(mouse, "zaxis", mouseZoom);

Ensure that any other binds for zaxis and alt m are commented out to avoid conflicts.  Also, if the file scripts/client/config.cs exists it will need to be deleted before changes to default.bind.cs can take effect.


Mouse Setup

The following code will change the way mouse input affects movement and click interaction.


Mouse Cursor Toggling

Normally, the camera is controlled by an actor in FPS (aim) mode. To focus on just mouse and camera work, we need to change how the default camera is controlled. Open game/scripts/server/gameCore.cs. In function GameCore::preparePlayer(%game, %client), locate the following line:

%game.spawnPlayer(%client, %playerSpawnPoint);


Change this code by adding a third argument to the function call:

%game.spawnPlayer(%client, %playerSpawnPoint, false);


The function call being modified is GameCore::spawnPlayer(%game, %this, %spawnPoint, %noControl), located in game/core/scripts/server/gameCore.cs. The last two arguments determine the location of spawning (%spawnPoint) and whether or not the actor object controls the camera (%noControl). We need to address that next.

Immediately below the %game.spawnPlayer() function, add the following code:

   // Set camera to Overhead mode   
   commandToServer('overheadCam');

If you run the game, you will now be using an orbit camera instead of an FPS view controlled by the actor. Next, we need to be able to control the on/off state of the in-game mouse cursor. Open game/scripts/client/default.bind.cs. At the end of the file, add the following:

// Turn mouse cursor on or off
// If %val is true, the button was pressed in
// If %val is false, the button was released
function toggleMouseLook(%val)
{
   // Check to see if button is pressed
   if(%val)  
   {
      // If the cursor is on, turn it off.
      // Else, turn it on
      if(Canvas.isCursorOn())
         hideCursor();
      else
         showCursor();
   }
}

// Bind the function toggleMouseLook to the keyboard 'm' key moveMap.bind(keyboard, "m", "toggleMouseLook");


Next, open your file browser and delete scripts/client/config.cs, if it exists. This file contains custom keybinds created for your game. It will override the variables and functions you add to default.bind.cs. However, if you delete this file and run your game, a new one will be regenerated with your updated keybinds.


If you start the game now, it will still default to a free flying (mouse look) camera. By hitting the 'm' key you will be able to toggle "mouse look" mode. If mouse look is on, you can control your view direction by moving the mouse. If it is off, you can move your cursor around on the screen. You can switch back to an actor controlled camera by pressing Alt + C.


We will go ahead and force the cursor to be on as soon as the level loads. Open game/art/gui/playGui.gui. You can edit .gui files just like any other script file. Look for the noCursor field. Make the following change to this field:

noCursor = "0";


Now that you've freed up the mouse from aiming duties, it's time to put it to other uses.


Placing Structures Using The GUI

First, open art/gui/PlayGui.gui and find new GuiControl(DamageHUD) toward the end of the file and remove the entire block of code (ensure that you do not delete the main block's closing brace - it's the one with the semi-colon after it).  It occupies the center of the screen when you are in play mode and it will block mouse clicks to that area.


Optionally, you can remove this control element using the Gui Editor.


Next, open the GUI Editor by pressing F10 or by clicking the GUI Editor button from the World Editor.


Open the Library tab, pull down the Buttons rollout,  then click and drag the GuiBitmapButtonCtrl onto the GUI to create a new button.


Select your new button and change the settings as follows:


Browse to your project's art/gui folder and select the orcburrow.png file for the button image.


If you close the GUI Editor ( F10 ) you should now see your button in the game UI.


Next, open scripts/gui/playGui.cs and add the following code at the end:

// onMouseDown is called when the left mouse
// button is clicked in the scene
// %pos is the screen (pixel) coordinates of the mouse click
// %start is the world coordinates of the camera
// %ray is a vector through the viewing
// frustum corresponding to the clicked pixel
function PlayGui::onMouseDown(%this, %pos, %start, %ray)
{
// If we're in building placement mode ask the server to create a building for
// us at the point that we clicked.
if (%this.placingBuilding)
{
// Clear the building placement flag first.
%this.placingBuilding = false;
// Request a building at the clicked coordinates from the server.
commandToServer('createBuilding', %pos, %start, %ray);
}
else
{
// Ask the server to let us attack a target at the clicked position.
commandToServer('checkTarget', %pos, %start, %ray);
}
}

// This function is the callback that handles our new button. When you click it // the button tells the PlayGui that we're now in building placement mode. function orcBurrowButton::onClick(%this) { PlayGui.placingBuilding = true; }


               Then, in <strong>scripts/server/commands.cs</strong> add the following function to the end:</p>
function serverCmdcreateBuilding(%client, %pos, %start, %ray)
{
    // find end of search vector
    %ray = VectorScale(%ray, 2000);
    %end = VectorAdd(%start, %ray);

    // set up to look for the terrain
    %searchMasks = $TypeMasks::TerrainObjectType;

    // search!
    %scanTarg = ContainerRayCast( %start, %end, %searchMasks);

    // If the terrain object was found in the scan
    if( %scanTarg )
    {
        // get the world position of the click
        %pos = getWords(%scanTarg, 1, 3);

        // Note:  getWord(%scanTarg, 0) will get the SimObject id of the object 
        // that the button click intersected with.  This is useful if you don't 
        // want to place buildings on certain other objects.  For instance, you 
        // could include TSStatic objects in your search masks and check to see 
        // what you clicked on - then don't place if it's another building.

        // spawn a new object at the intersection point
        %obj = new TSStatic()
        {
            position = %pos;
            shapeName = "art/shapes/building/orcburrow.dts";
            collisionType = "Visible Mesh";
            scale = "0.5 0.5 0.5";
        };

        // Add the new object to the MissionCleanup group
        MissionCleanup.add(%obj);
    }
}
            <p><br />If you run the game now, you should be able to click the button, then click 
                on the ground to place a new orc burrow.
            </p>
            <p><a href="images/RTS_PlaceBurrow.png" class="livethumbnail">
                <img alt="" src="images/RTS_PlaceBurrow.png" width="308", height="240" largewidth="615" largeheight="480" /></a></p>
              <p><br />
                    Optionally, you can remove the DamageHUD element from the PlayGui - it is not useful in a strategy game and it happens
                    to block mouse clicks.
              </p>
              <p><a href="images/RTS_RemoveDamageHUD.png" class="livethumbnail">
              <img alt="" src="images/RTS_RemoveDamageHUD.png" width="600" height="420" largewidth="1379" largeheight="889" /></a><br /></p>
            <a name="Mouse-Driven_Input" id="Mouse-Driven_Input"></a>
            <h2> <span class="mw-headline">Mouse-Driven Input</span></h2>
            <p>Without FPS controls and player aiming, we need a new way to control
              the Player object. The best examples of a mouse driven game genre are RTS
              and Hack &amp; Slash. Typically, these game types allow you to move and
              attack using the mouse buttons. Let's start with movement.  </p><br />
            <a name="Player_Spawning" id="Player_Spawning"></a>
            <h3> <span class="mw-headline">Player Spawning</span></h3>
            <p>At this point, we can spawn an AI player to stand in for the stock player using 
                the default player class settings we&#39;ve provided in the 
                DeathMatchGame::initGameVars() method.
              This AI will be controlled by our mouse inputs. In addition, Torque 3D uses a
              simple spawn system which can be easily modified to spawn any kind of
              object (of any class).&nbsp; This section will demonstrate how to select what type 
                of player or NPC you would like to spawn at a particular spawn point.</p>
              <p><br />Open Toolbox, select the <b>empty terrain</b> level, then click the World Editor button. </p>
            <p><br />
              Once you are in the editor, locate the spawn sphere in the 
                scene. It is represented by a green octahedron, which will display a green
              sphere when you click on it: </p>
            <br />
            <p><i>(click to enlarge)</i> </p>
            <a href="images/RTS_SpawnSphere.png" class="livethumbnail">
              <img src="images/RTS_SpawnSphere.png" width="320" height="247" largewidth="640" 
                  largeheight="495" /></a><br />
            <p><br /><br />
              You can also locate a spawn sphere by browsing the Scene Tree, under the PlayerDropPoints SimGroup: </p>
            <p><br />
              <img alt="Image:RTS_SpawnSphere2.jpg" src="images/RTS_SpawnSphere2.png" 
                    border="0" /> </p>
            <p><br />
              If you have multiple spawn spheres, delete all except for one. We can
              control what type of actor is spawned by changing the properties of the
              remaining spawn sphere. Select the sphere, then change the spawnClass
              to <b>AIPlayer</b> and spawnDatablock to <b>BoomBotData.</b> Also, change the name of the spawn sphere to <b>PlayerSpawn</b>.&nbsp; 
                Technically this step is optional, but if you add other player types you will 
                want to be able to specify who spawns where.&nbsp; This mechanism allows you to 
                do that with minimal effort.</p>
            <p><br />
              <img alt="Image:RTS_SpawnProperties.jpg" src="images/RTS_SpawnProperties.png" 
                    border="0" /> </p>
              <p>This basically replicates the change we made in script earlier, but only for this 
                  specific spawn point.&nbsp; You could as easily used MyBossData for the 
                  spawnDatablock field and then that spawnpoint would spawn MyBoss objects.</p><br />
            <a name="Movement" id="Movement"></a>
            <h3> <span class="mw-headline">Movement</span></h3>
            <p>Now that we have an AI player spawning in the game, we can send it commands. Open <b>game/scripts/gui/playGui.cs</b>. Add the function <b>onRightMouseDown</b> as follows: </p>
            <pre>// onRightMouseDown is called when the right mouse

// button is clicked in the scene // %pos is the screen (pixel) coordinates of the mouse click // %start is the world coordinates of the camera // %ray is a vector through the viewing // frustum corresponding to the clicked pixel function PlayGui::onRightMouseDown(%this, %pos, %start, %ray) {
commandToServer('movePlayer', %pos, %start, %ray); }


At the end of scripts/server/commands.cs add the following:

function serverCmdmovePlayer(%client, %pos, %start, %ray)
{
   //echo(" -- " @ %client @ ":" @ %client.player @ " moving");
   
   // Get access to the AI player we control
   %ai = %client.player;

   %ray = VectorScale(%ray, 1000);
   %end = VectorAdd(%start, %ray);

   // We want to allow the AI Player to walk on TSStatics, Interiors, Terrain, etc., so 
   // I broadened the search mask selection.
   %searchMasks = $TypeMasks::TerrainObjectType | $TypeMasks::StaticTSObjectType | 
       $TypeMasks::InteriorObjectType | $TypeMasks::ShapeBaseObjectType | 
       $TypeMasks::StaticObjectType;

   // search!
   %scanTarg = ContainerRayCast( %start, %end, %searchMasks);

   // If the terrain object was found in the scan
   if( %scanTarg )
   {
      %pos = getWords(%scanTarg, 1, 3);
      // Get the normal of the location we clicked on
      %norm = getWords(%scanTarg, 4, 6);
      
      // Set the destination for the AI player to
      // make him move
      %ai.setMoveDestination( %pos );
   }
}
            <p><br />
              Save your script and run the game. You should now be able to
              direct the AI player to wherever you right-click on the terrain. This
              only works if you have mouse look disabled, and your cursor is present
              on screen. </p><br />
            <a name="Spawning_Enemy_Targets" id="Spawning_Enemy_Targets"></a>
            <h3> <span class="mw-headline">Spawning Enemy Targets</span></h3>
            <p>Our player looks lonely and bored. We should give him some targets, and the means of disposing them. Open <b>game/scripts/client/default.bind.cs</b>, and add the following to the bottom of the file: </p>
            <pre>// Spawn an AI guy when key is pressed down

function spawnAI(%val) { // If key was pressed down if(%val) { // Create a new, generic AI Player // Position will be at the camera's location // Datablock will determine the type of actor new AIPlayer() { position = LocalClientConnection.camera.getPosition(); datablock = "DefaultPlayerData"; }; } }

// Bind the function spawnAI to the keyboard 'b' key moveMap.bind(keyboard, b, spawnAI);


In the above code, a new example of accessing a client connection is shown. Instead of ClientGroup, the code uses LocalClientConnection. In a "single player" environment, you can use these two interchangeably. Due to Torque 3D's architecture, there will always be a server and at least one client connection.


The common practice for choosing which to use is as follows:

  • Accessing From A Client - Use LocalClientConnection. This will always access your connection, player, camera, etc.
  • Accessing From Server - Use ClientGroup.getObject(%index). Multiple connections to choose from. This is good for applying the same functionality to all connections, or isolating specific ones based on ID.


Again, do not forget to delete game/scripts/client/config.cs. You can run the game, then press the 'b' key to spawn stationary AI targets in the same position as your camera. If gravity is enabled, they will fall until they hit the terrain.


Attacking

Currently, we have a player we can control, and targets that can die. Let's give the player some combat skills. In game/scripts/server/commands.cs, add the following two functions to the bottom of the script:

function serverCmdcheckTarget(%client, %pos, %start, %ray)
{
%player = %client.player;

%ray = VectorScale(%ray, 1000); %end = VectorAdd(%start, %ray);

// Only care about players this time %searchMasks = $TypeMasks::PlayerObjectType;

// Search! %scanTarg = ContainerRayCast( %start, %end, %searchMasks);

// If an enemy AI object was found in the scan if( %scanTarg ) { // Get the enemy ID %target = firstWord(%scanTarg); if(%player != %target) { // Cause our AI object to aim at the target // offset (0, 0, 1) so you don't aim at the target's feet %player.setAimObject(%target, "0 0 1");

     // Tell our AI object to fire its weapon
     %player.setImageTrigger(0, 1);
  }
  else
  {
     serverCmdstopAttack(%client);
  }

} else { serverCmdstopAttack(%client); } }

function serverCmdstopAttack(%client) { // If no valid target was found, or left mouse // clicked again on terrain, stop firing and aiming %unit = %client.player; %unit.setAimObject(0); %unit.schedule(150, "setImageTrigger", 0, 0); }


Notice that we're using the full function name when calling serverCmdstopAttack() from within serverCmccheckTarget(). Since we're in a serverCmd function we're not actually sending a command to the server because right now we are the server. So in this circumstance (and, coincidentally the same applies to clientCmd functions) we just call the full function directly. It is good to leave this as a serverCmd function because you might want the client to be able to request a unit (or all of his units) to stop attacking in some other situation.


Now, your player will continuously shoot at any other player you left click on (accuracy not guaranteed). Press the 'b' key to spawn targets to shoot at and blast away. The AI player will be locked in auto-fire mode until you left click on the terrain or on another target. or on another target.


We now have the base functionality for moving the player and the camera, selecting a target, and attacking is now complete.


Tweaking Attacks

You might have noticed some flaws with the base code:

  • The first shot usually misses
  • AI keeps shooting after enemy is dead
  • Enemy does not appear to "die" when health reaches 0


We are going to try and correct these one at a time using TorqueScript and the editors. Let's start by making our first shot be on target. The reason the first shot may miss entirely is because the AI is firing before it has fully turned to aim at the target.


To fix this, edit scripts/server/commands.cs., scroll down to the serverCmdcheckTarget() function, and locate the following line of code:

// Tell our AI object to fire its weapon
%player.setImageTrigger(0, 1);


Replace the above code with the following:

// Tell our AI object to fire its weapon in 100 milliseconds
%player.schedule(100, "setImageTrigger", 0, 1);


Remember, the %ai variable contains a handle to our AI player object. The AIPlayer object, which is a child class of SimObject, can make use of a method named schedule. Instead of calling the setImageTrigger function immediately, we can schedule it to go off in delayed manner.


Schedule (ConsoleMethod) Parameters

simObject.schedule(time, command, arg1...argN)
  • time - Number of milliseconds to wait before calling the command.
  • command - Member function (belonging to the simObject using schedule) to call
  • arg1...argN - Parameters, comma separated, to pass into the command.


The AI we control should now have time to turn and face the target before firing off the first shot. The code is currently delayed by 100 milliseconds, so you can adjust that number based on desired performance.


Next, we will change the auto-fire behavior. Instead of having the AI constantly attack a target, even after it is dead, we are going to modify the code to only cause our player to attack when a mouse button is clicked. In the same function we were just working in, locate the first schedule line we created

// Tell our AI object to fire its weapon in 100 milliseconds
%player.schedule(100, "setImageTrigger", 0, 1);


Then add the following directly under it:

// Stop firing in 150 milliseconds
%player.schedule(150, "setImageTrigger", 0, 0);


If you have not been saving after every script change, you should definitely do so. Save, then run your game to test the changes made to the attack routine. Your AI should now be facing the target on the first shot, and only attack when you click on the target.


There is one more change we can make to make the combat provide more feedback. Each enemy AI starts with health, which is diminished each time it gets shot. The Full template this tutorial is based on is originally intended for a FPS deathmatch game. When an actor dies, a death animation is played.


The death animation code can be found in game/scripts/server/player.cs. Open this file, then scroll down to the following function:


function Player::playDeathAnimation(%this)
{
if (isObject(%this.client))
{
if (%this.client.deathIdx++ > 11)
%this.client.deathIdx = 1;
%this.setActionThread("Death" @ %this.client.deathIdx);
}
else
{
%rand = getRandom(1, 11);
%this.setActionThread("Death" @ %rand);
}
}


The template uses Gideon as the stock actor. The model ships with 11 death animations, which are labeled as "death#" (where # is 1 - 11). This works well for a Player constantly dying, but for an AIPlayer in this tutorial, we only need 1 death animation. This tutorial also mainly works as a client side (single player) prototype.


In simpler terms, we do not need to use the death index (.deathIdx) or %client variables. We can simply call the first death animation available. Change the ::playDeathAnimation(...) function to the following:

function Player::playDeathAnimation(%this)
{
%this.setActionThread("Death1");
}

Now, when the target AI loses all its health it will play a death animation and eventually disappear.


Next, you may notice that the AI units still have terrible aim. This is because the weapons are all set up to be used in first person mode. Any weapon that you intend to use with these AI units needs to be modified before they can be used effectively. Find your weapon datablock files in game/art/datablocks/weapons and search for LurkerWeaponImage (to use the Lurker datablock file as an example) then find useEyeNode and firstPerson. Change any instances of these from true to false. You can also experiment with correctMuzzleVector as well. You should find a block like the following, except at the end you will see some additions that should help.

   // Specify mount point & offset for 3rd person, and eye offset
   // for first person rendering.
   mountPoint = 0;
   firstPerson = false;
   useEyeNode = false;
   animateOnServer = true;

   // Add these to get BoomBot to aim correctly
   useEyeOffset = true;
   eyeOffset = "0 0 -0.35";
              <p><br />
              Fiddling with the eyeOffset vector may provide fine-tuning control over aiming, but I haven't been able to see any drastic difference.  Don't be afraid to experiment.
              </p>
              <p><br />
              As a bit of an aside, if you intend to be able to control units in a game with mixed AI and human players where the humans might be in first person control you will 
              want to make a copy of all of your weapon datablocks and make the above modifications to them instead.  You'll have to name your new datablocks to something like 
              <strong>BotLurkerWeaponImage</strong> and load your AI players out with these versions of the weapons instead of the unmodified weapons that you use for the human 
              players.
              </p>
              <br />
            <a name="Destination_Markers" id="Destination_Markers"></a>
            <h2> <span class="mw-headline">Destination Markers</span></h2>
            <p>In most RTS or Hack &amp; Slash games, some kind of marker is placed
              on the ground where you clicked. This is usually a visual aid to let
              you know the move assignment was given, the destination has been set,
              and the AI is moving. . </p>
            <p><br />
              We are going to add this functionality to our prototype to
              make it easier to track our AI player using the Material Editor, Decal
              Editor, and TorqueScript. First, we need to create a material for the
              marker. </p><br />
            <a name="Creating_a_Material" id="Creating_a_Material"></a>
            <h3> <span class="mw-headline">Creating a Material</span></h3>
            <p>To get started on our marker creation, run your project in the <strong>World Editor</strong>. Next, open the 
                <strong>Material Editor</strong> and click on the <i>Create New Material</i> button. </p>
            <p><br />
              <img alt="Image:MarkerNewMaterialButton.jpg" 
                    src="images/RTS_MarkerNewMaterialButton.png" border="0" /> </p>
            <p><br />
              At this point, the current material will be switched to an 
                orange warning texture signifying that no diffuse map has been applied. Change the Material name to "gg_marker" and press enter to apply the
              change. Next, click on the Diffuse Map box to open the file browser.
              Navigate to the <b>game/art/decals</b> folder and select the g_marker.png file. This asset was given to you at the beginning of this guide: </p>
            <p><br />
              <i>(click to enlarge)</i> </p>
            <a href="images/RTS_MarkerFile.png" class="livethumbnail">
              <img src="images/RTS_MarkerFile.png" width="320" height="247" largewidth="640" 
                  largeheight="495" /></a><br />
            <p><br />
              Your new material is nearly complete. However, you should notice that
              the marker file and the material do not look the same. Compare the two: </p>
            <p><br />
              <b>Marker File</b> </p>
            <p><img alt="Image:g_marker.png" src="images/G_marker.png" border="0" height="253" width="253" /> </p>
            <p><br />
              <b>Material</b> </p>
            <p><img alt="Image:gMaterialBefore.jpg" src="images/RTS_GMaterialBefore.png" 
                    border="0" /> </p>
            <p><br />
              This is easy to fix. While editing the gg_marker material,
              go to the very bottom in the Advanced Properties section and make the indicated 
                changes:<br /></p>
            <p>
              <img alt="Image:toggleAlphaThreshold.jpg" 
                    src="images/RTS_ToggleAlphaThreshold.png" border="0" /> </p>
            <p><br />
              This will immediately change the material preview.&nbsp; If you see something like 
                the following, don&#39;t worry; this will probably look fine when we apply it to the 
                decal.</p>
              <p>
                  <img alt="" dir="ltr" src="images/RTS_DecalMaterialPreview.png" /></p>
            <p><br />
              You are finished with the material. Click save the save button, which will write out the following data to <b>game/art/material.cs:</b> </p>
            <pre>singleton Material(gg_marker)

{ mapTo = "unmapped_mat"; diffuseMap[0] = "art/markers/g_marker.png"; alphaTest = "1"; alphaRef = "80"; };


This is the benefit of using the visual editor to create your materials and decals, instead of manually writing them out in TorqueScript. Let's move on to creating the decal.


Creating a Decal

To create a marker decal, run the World Editor and then open the Decal Editor.

Click on the New Decal Data button ( ), next to the garbage bin ( ), and name your new entry "gg_decal".


Image:MarkerNewDecal.jpg


Next, click on the box in the Material Field of the decal properties, as shown below:


This should open the Material Selector. Locate the gg_maker material we created earlier, click on it, then press the Select button:


(click to enlarge)



The Decal Editor's preview box will display what your new decal will look like in the scene.


(click to enlarge)



That's all that needs to be done to create the decal. Save your level, and your decal data will automatically be written out to game/art/decals/managedDecalData.cs:

datablock DecalData(gg_decal)
{
textureCoordCount = "0";
Material = "gg_marker";
};

Spawning the Marker

Now that we have a destination marker, we need to add it upon clicking on the terrain and then delete it when our player reaches its destination. Start by opening game/scripts/gui/playGui.cs. Find the PlayGui::onRightMouseDown function. At the end of this function, add the following code:

     %ray = VectorScale(%ray, 1000);
%end = VectorAdd(%start, %ray);
// only care about terrain objects
%searchMasks = $TypeMasks::TerrainObjectType | $TypeMasks::StaticTSObjectType | 
    $TypeMasks::InteriorObjectType | $TypeMasks::ShapeBaseObjectType |
    $TypeMasks::StaticObjectType;

// search!
%scanTarg = ContainerRayCast( %start, %end, %searchMasks);

if (%scanTarg)
{
    // Get access to the AI player we control
    %ai = LocalClientConnection.player;

    // Get the X,Y,Z position of where we clicked
    %pos = getWords(%scanTarg, 1, 3);

    // Get the normal of the location we clicked on
    %norm = getWords(%scanTarg, 4, 6);

    // If the AI player already has a decal (0 or greater)
    // tell the decal manager to delete the instance of the gg_decal
    if(%ai.decal > -1)
    {
        decalManagerRemoveDecal(%ai.decal);
    }

    // Create a new decal using the decal manager
    // arguments are (Position, Normal, Rotation, Scale, Datablock, Permanent)
    // AddDecal will return an ID of the new decal, which we will
    // store in the player
    %ai.decal = decalManagerAddDecal(%pos, %norm, 0, 1, "gg_decal", true);
}


Save your script, then run the game. When you right click on the terrain, the GarageGames symbol should render as a decal at the destination.


(click to enlarge)




Erasing the Marker

The last thing we need to do is erase the destination marker when our AI player gets to it. Open the game/art/datablocks/BoomBot.cs file, then add the following:

// This is a callback function
// This is automatically called by the engine as part 
// of the AI routine
// %this - The BoomBotData datablock
// %obj - The instance of this datablock (our AI Player)
function BoomBotData::onReachDestination(%this, %obj)
{
   // If there was a decal placed, then it was
   // stored in this %obj variable (see playGui.cs)
   // Erase the decal using the decal manager
   if( %obj.decal > -1 )
      decalManagerRemoveDecal(%obj.decal);
}


Now, when the AI player reaches its destination the marker will be deleted.


Camera Modes

Now that you've got control of your character, it's time to discuss the camera controls. We've decided on a two-mode approach so that you can use the Overhead mode to observe the battlefield and the OrbitObject mode so that you can follow a specific unit.


Orbit Camera


Open the scripts/server/commands.cs script and find the serverCmdorbitCam() function:

function serverCmdorbitCam(%client)
{
   %client.camera.setOrbitObject(%client.player, mDegToRad(20) @ "0 0", 0, 5.5, 5.5);
   %client.camera.camDist = 5.5;
   %client.camera.controlMode = "OrbitObject";
}


Lets break this command down. %client.camera.setOrbitObject() puts the camera into OrbitObject mode. The first argument is the object to orbit around.  %client is provided by our caller when the server command is called. 


The second argument is a vector representing the angle of the camera in (x, y, z) or (pitch, roll, yaw) if you prefer. Here it is pitched 20 degrees down, with 0 roll and 0 yaw.


The next three arguments are the allowed distances from the target: min distance, max distance and current distance: here 0, 5.5 and 5.5 respectively. The last two arguments should be sent as floating point numbers or odd results can occur.  This function may take additional optional parameters: an ownership flag denoting if the object orbited by the camera belongs to the camera's client, an offset if the camera should focus somewhere other than the object's center, and a flag specifying if the camera should be locked.


The next line sets the camera distance from the orbit target to 5.5 units.


The final line sets the controlMode to OrbitObject.


Overhead Camera

Cameras used by RTS games are slightly different from the Hack & Slash or Fly cameras. They are characterized by a camera that moves laterally along the x and y axis, but generally not in z. This can be realized in T3D by using the "Overhead" camera mode.


In scripts/server/commands.cs find the serverCmdoverheadCam() function:

function serverCmdoverheadCam(%client)
{
   %client.camera.position = VectorAdd(%client.player.position, "0 0 30");
   %client.camera.lookAt(%client.player.position);
   %client.camera.controlMode = "Overhead"; 
}


With this setup, the camera will be free to move around with the standard "wasd" controls, but it will not move vertically in the world. By default the 'e' key should move the camera up and the 'c' key should move the camera down if you want to adjust the camera's height above the terrain.


For the traditional RTS players who wish to use the mouse wheel, we implemented mouse wheel zoom in this function from the Camera Setup section (scripts/server/commands.cs):

// Adjusts the height of the camera using the mouse wheel
function serverCmdadjustCamera(%client, %adjustment)
{
   if(%client.camera.controlMode $= "OrbitObject")
   {
      if(%adjustment == 1)
         %n = %client.camera.camDist + 0.5;
      else
         %n = %client.camera.camDist - 0.5;
  if(%n < 0.5)
     %n = 0.5;
     
  if(%n > 15)
     %n = 15.0;
     
  %client.camera.setOrbitObject(%client.player, %client.camera.getRotation(), 
    0, %n, %n);
  %client.camera.camDist = %n;

} if(%client.camera.controlMode $= "Overhead") { %client.camera.position = VectorAdd(%client.camera.position, "0 0 " @ %adjustment); } }

Notice that this function catches the camera mode and uses an appropriate method for adjusting the camera's position by checking the controlMode member's value.


In the above code, we are sticking to the client/server architecture of Torque 3D. Typically, actions such as navigating through GUIs, rendering, and input are handled on the client. However, when actions have an effect on the game, they should be performed on the server.


Camera location can usually be handled as a client operation, but this is a good opportunity to show off the client/server communication. Also, in multiplayer games it is important to remember that the server scopes visibility for the clients. Camera position should stay in sync to ensure that this scoping is accurate.  The default.bind.cs is a client script, which contains the client function mouseZoom(...). This is only called when there is a client action, such as the mouse wheel input.


Once the client action has been performed, a message is sent to the server to act on it: commandToServer('adjustCamera', -1);. The first parameter is the name of the server command/function to call (minus the serverCmd prefix), and the rest of the parameters are arguments used by the command. In this situation, based on the direction of the mouse wheel rotation a positive or negative 1 will be sent to the server command which uses this value to adjust the camera.


Now that the functions are set up, all that is left is creating a key bind to call them. Back in default.bind.cs we added the following binding to the script:

moveMap.bind( mouse, zaxis, mouseZoom );

This allows you to zoom in and out on your actor using your mouse's scroll wheel in orbit mode and adjust camera height in overhead mode..


If you want to play around with the camera settings created in this tutorial, examine the following code that we added at the bottom of game/scripts/server/commands.cs in the Camera Setup section.

function serverCmdorbitCam(%client)
{
   %client.camera.setOrbitObject(%client.player, mDegToRad(20) @ "0 0", 0, 5.5, 5.5);
   %client.camera.camDist = 5.5;
   %client.camera.controlMode = "OrbitObject";
}

function serverCmdoverheadCam(%client)
{
   %client.camera.position = VectorAdd(%client.player.position, "0 0 30");
   %client.camera.lookAt(%client.player.position);
   %client.camera.controlMode = "Overhead"; 
}

function serverCmdtoggleCamMode(%client)
{
   if(%client.camera.controlMode $= "Overhead")
   {
      %client.camera.setOrbitObject(%client.player, mDegToRad(20) @ "0 0", 0, 5.5, 5.5);
      %client.camera.camDist = 5.5;
      %client.camera.controlMode = "OrbitObject";
   }
   else if(%client.camera.controlMode $= "OrbitObject")
   {
      %client.camera.controlMode = "Overhead"; 
      %client.camera.position = VectorAdd(%client.player.position, "0 0 30");
      %client.camera.lookAt(%client.player.position);
   }
}
            <p><br />
              You can call these functions using the usual <strong>commandToServer</strong> syntax. Just type the following in the console (press ~) </p>
commandToServer('orbitCam');

commandToServer('overheadCam');

            <a name="GoingRTS" id="A3"></a>
            <h2> <span class="mw-headline">Going More Real-Time Strategy</span></h2>
            <p>Here we&#39;re going to talk about what to do with that orc burrow.&nbsp; We need a 
                place to get more friendly units and the burrow seems the logical place, but it 
                needs a few adjustments to work.&nbsp; I&#39;m not going into resource costs or 
                build times - call them exercises for the reader - we&#39;re just going to pop out a 
                new friendly unit when you left-click on the burrow.</p>
              <p><br />First, we&#39;ll add some code to the <strong>serverCmdcheckTarget()</strong function to handle spawning.&nbsp; The 
                function should look something like this:</p>
function serverCmdcheckTarget(%client, %pos, %start, %ray)
{
    %ray = VectorScale(%ray, 1000);
    %end = VectorAdd(%start, %ray);

    // Add new typemasks to the search so we can find clicks on barracks too
    %searchMasks = $TypeMasks::PlayerObjectType | $TypeMasks::StaticTSObjectType
         | $TypeMasks::StaticObjectType;

    // Search!
    %scanTarg = ContainerRayCast( %start, %end, %searchMasks);

    // If an enemy AI object was found in the scan
    if( %scanTarg )
    {
        // Get the enemy ID
        %target = firstWord(%scanTarg);
        if (%target.class $= "barracks")
        {
            serverCmdspawnTeammate(%client, %target);
        }
        else if (%target.getClassName() $= "AIPlayer")
        {
            if (%target.team != 1)
            {
                // Cause our AI object to aim at the target
                // offset (0, 0, 1) so you don't aim at the target's feet

                if (isObject(Team1List))
                {
                    %c = 0;
                    %unit = Team1List.getObject(0);
                    while (isObject(%unit))
                    {
                        if (%unit.isSelected)
                        {
                            %unit.mountImage(Lurker, 0);
                            %targetData = %target.getDataBlock();
                            %z = getWord(%targetData.boundingBox, 2) * 2;
                            %offset = "0 0" SPC %z;
                            %unit.setAimObject(%target, %offset);

                            // Tell our AI object to fire its weapon
                            %unit.setImageTrigger(0, 1);
                        }
                        %c++;
                        %unit = Team1List.getObject(%c);
                    }
                }
            }
            else
            {
                if ($SelectToggled)
                {
                    multiSelect(%target);
                }
                else
                {
                    cleanupSelectGroup();
                    %target.isSelected = true;
                    %target.isLeader = true;
                }
            }
        }
        else
        {
            serverCmdstopAttack(%client);
            if (!$SelectToggled)
                cleanupSelectGroup();
        }
    }
    else
    {
        serverCmdstopAttack(%client);
        if (!$SelectToggled)
            cleanupSelectGroup();
    }
}
            <p>
                I also added some support code for handling selection of multiple units and a little bit for 
                spawning new bots from our orc burrows.
            </p>

            <p><br />
                Add the following code in  <strong>scripts/server/gameCore.cs</strong> at the end of the <strong>GameCore::spawnPlayer()</strong> function.
            </p>
   %player.team = 1;

    if (!isObject(Team1List))
    {
        new SimSet(Team1List);
        MissionCleanup.add(Team1List);
    }
    
    Team1List.add(%player);
            <p><br />
                This ties in with our new multi-select system so that you can continue to select and control the original player object.
            </p>

            <p><br />
                We'll need to revisit <strong>serverCmdstopAttack()</strong> to handle our multi-select system, too.  It should look like this:
            </p>
function serverCmdstopAttack(%client)
{
    // If no valid target was found, or left mouse
    // clicked again on terrain, stop firing and aiming
    for (%c = 0; %c < Team1List.getCount(); %c++)
    {
        %unit = Team1List.getObject(%c);
        %unit.setAimObject(0);
        %unit.schedule(150, "setImageTrigger", 0, 0);
    }
}
            <p><br />
                Next, we'll add some more server commands to help us with managing our army.&nbsp;&nbsp; 
                Our first step is to extend our <strong>serverCmdcreateBuilding()</strong> function to include a 
                new spawn point that is associated with the structure to use as our troop 
                creation point.&nbsp; The new version should look like this:</p>
function serverCmdcreateBuilding(%client, %pos, %start, %ray)
{
    // find end of search vector
    %ray = VectorScale(%ray, 2000);
    %end = VectorAdd(%start, %ray);

    %searchMasks = $TypeMasks::TerrainObjectType;

    // search!
    %scanTarg = ContainerRayCast( %start, %end, %searchMasks);

    // If the terrain object was found in the scan
    if( %scanTarg )
            %obj = getWord(%scanTarg, 0);

        %pos = getWords(%scanTarg, 1, 3);

        // spawn a new object at the intersection point
        %obj = new TSStatic()
        {
            position = %pos;
            shapeName = "art/shapes/building/orcburrow.dts";
            class = "barracks";
            collisionType = "Visible Mesh";
            scale = "0.5 0.5 0.5";
        };

        // Add the new object to the MissionCleanup group
        MissionCleanup.add(%obj);
        
        // Set up a spawn point for new troops to arrive at.
        if (!isObject(Team1SpawnGroup))
        {
            new SimGroup(Team1SpawnGroup)
            {
                canSave = "1";
                canSaveDynamicFields = "1";
                    enabled = "1";
            };

            MissionGroup.add(Team1SpawnGroup);
        }
        
        %spawnName = "team1Spawn" @ %obj.getId();
        %point = new SpawnSphere(%spawnName)
        {
            radius = "1";
            dataBlock      = "SpawnSphereMarker";
            spawnClass     = $Game::DefaultPlayerClass;
            spawnDatablock = $Game::DefaultPlayerDataBlock;
        };
        %point.position = VectorAdd(%obj.getPosition(), "0 5 2");
        Team1SpawnGroup.add(%point);
        MissionCleanup.add(%point);
    }
}
            <p>
                Next we'll add a function to spawn a new bot and equip it with a weapon and some ammo.
            </p>
function serverCmdspawnTeammate(%client, %source)
{
    // Create a new, generic AI Player
    // Position will be at the camera's location
    // Datablock will determine the type of actor
    %spawnName = "team1Spawn" @ %source.getId();

    // Defaults
    %spawnClass      = $Game::DefaultPlayerClass;
    %spawnDataBlock  = $Game::DefaultPlayerDataBlock;

    // Overrides by the %spawnPoint
    if (isDefined("%spawnName.spawnClass"))
    {
     %spawnClass = %spawnName.spawnClass;
     %spawnDataBlock = %spawnName.spawnDatablock;
    }
    else if (isDefined("%spawnName.spawnDatablock"))
    {
     // This may seem redundant given the above but it allows
     // the SpawnSphere to override the datablock without
     // overriding the default player class
     %spawnDataBlock = %spawnName.spawnDatablock;
    }

    %spawnProperties = %spawnName.spawnProperties;
    %spawnScript     = %spawnName.spawnScript;

    // Spawn with the engine's Sim::spawnObject() function
    %newBot = spawnObject(%spawnClass, %spawnDatablock, "",
                        %spawnProperties, %spawnScript);

    %spawnLocation = GameCore::pickPointInSpawnSphere(%newBot, %spawnName);
    %newBot.setTransform(%spawnLocation);
    %newBot.team = 1;

    %newBot.clearWeaponCycle();

    %newBot.setInventory(Lurker, 1);
    %newBot.setInventory(LurkerClip, %newBot.maxInventory(LurkerClip));
    %newBot.setInventory(LurkerAmmo, %newBot.maxInventory(LurkerAmmo));
    %newBot.addToWeaponCycle(Lurker);

    if (%newBot.getDatablock().mainWeapon.image !$= "")
    {
        %newBot.mountImage(%newBot.getDatablock().mainWeapon.image, 0);
    }
    else
    {
        %newBot.mountImage(Lurker, 0);
    }
    
    // This moves our new bot away from the front door a ways to make room for 
    // other bots as we spawn them.
    %x = getRandom(-10, 10);
    %y = getRandom(4, 10);
    %vec = %x SPC %y SPC "0";
    %dest = VectorAdd(%newBot.getPosition(), %vec);
    %newBot.setMoveDestination(%dest);
    
    addTeam1Bot(%newBot);
}
            <p>
                We also need our <strong>addTeam1Bot()</strong> support function:
            </p>
function addTeam1Bot(%bot)
{
    // We'll create a SimSet to track our Team1 bots if it hasn't been created already
    if (!isObject(Team1List))
    {
        new SimSet(Team1List);
        MissionCleanup.add(Team1List);
    }
    
    // And then add our bot to the Team1 list.
    Team1List.add(%bot);
}
            <p>
                At this point we're ready to spawn units from our structures.&nbsp;&nbsp; If you 
                test the game now, you should be able to create a new burrow and it should spawn 
                bots when you click on it.</p>
              <p><br />
                  <img alt="" src="images/RTS_SpawnBotsFromBuilding.png" /></p>
            <p><br />
                A real-time strategy game isn&#39;t much unless you can select and direct your 
                units.&nbsp; Next, we&#39;ll add a few more server commands and a client command to 
                help with selecting and moving single and multiple units.</p>
            <p><br />
                First we&#39;ll add the ability to &quot;select&quot; multiple units.&nbsp;&nbsp; 
                Still in <strong>scripts/server/commands.cs</strong>, add the following 
                functions:</p>
function serverCmdtoggleMultiSelect(%client, %flag)
{
    if (%flag)
        $SelectToggled = true;
    else
        $SelectToggled = false;
}

function multiSelect(%target)
{
    if (!isObject(Team1List))
    {
        new SimSet(Team1List);
        MissionCleanup.add(Team1List);
    }
    
    %leader = findTeam1Leader();
    if (isObject(%leader))
    {
        %target.destOffset = VectorSub(%leader.getPosition(), %target.getPosition());
    }
    else
    {
        %target.destOffset = "0 0 0";
        %target.isLeader = true;
    }

    %target.isSelected = true;
}

function findTeam1Leader()
{
    if (!isObject(Team1List))
    {
        new SimSet(Team1List);
        MissionCleanup.add(Team1List);
    }

    for (%c = 0; %c < Team1List.getCount(); %c++)
    {
        %unit = Team1List.getObject(%c);
        if (%unit.isLeader)
            return %unit;
    }

    return 0;
}

function cleanupSelectGroup()
{
    if (!isObject(Team1List))
    {
        new SimSet(Team1List);
        MissionCleanup.add(Team1List);
    }
    
    for (%c = 0; %c < Team1List.getCount(); %c++)
    {
        %temp = Team1List.getObject(%c);
        %temp.isSelected = false;
        %temp.isLeader = false;
        %temp.destOffset = "0 0 0";
    }
}
            <p>
                First, 
                <strong>serverCmdtoggleMultiSelect()</strong> just takes a flag and sets a global variable to let 
                the system know when we want to start adding units to our selection list.&nbsp; 
                The <strong>multiSelect()</strong> function actually handles setting up&nbsp; 
                the list by setting a member variable on the bot to indicate that it has been 
                selected.&nbsp; Additionally, if there is no other bot in the Team1List SimSet 
                that is selected this bot is designated the &quot;leader.&quot;&nbsp; All of the 
                subsequently selected bots will calculate offset destination targets based on 
                this bot&#39;s destination.&nbsp; The <strong>findTeam1Leader()</strong> 
                utility function just searches the Team1List for a designated &quot;leader&quot; unit.&nbsp; 
                Finally, the <strong>cleanupSelectGroup()</strong> utility function just clears the 
                selection variables from all of Team1List&#39;s members.
            </p>
            <p><br />
                Next, modify <strong>PlayGui::onRightMouseDown()</strong> in <strong>scripts/gui</strong> so that it 
                looks like the following:
            </p>
function PlayGui::onRightMouseDown(%this, %pos, %start, %ray)
{   
    commandToServer('movePlayer', %pos, %start, %ray);
    
    %ray = VectorScale(%ray, 1000);
    %end = VectorAdd(%start, %ray);

    // only care about terrain objects
    %searchMasks = $TypeMasks::TerrainObjectType | $TypeMasks::StaticTSObjectType | 
    $TypeMasks::InteriorObjectType | $TypeMasks::ShapeBaseObjectType
    | $TypeMasks::StaticObjectType;

    // search!
    %scanTarg = ContainerRayCast( %start, %end, %searchMasks);

    if (%scanTarg)
    {
        %obj = getWord(%scanTarg, 0);

        // Get the X,Y,Z position of where we clicked
        %pos = getWords(%scanTarg, 1, 3);

        // Get the normal of the location we clicked on
        %norm = getWords(%scanTarg, 4, 6);

        // Create a new decal using the decal manager
        // arguments are (Position, Normal, Rotation, Scale, Datablock, Permanent)
        // We are now just letting the decals clean up after themselves.
        decalManagerAddDecal(%pos, %norm, 0, 1, "gg_decal", false);
    }
}
        <p>
            This change eliminates the need to track which bot is the &quot;leader&quot; and which bot 
            which decal belongs to - it simply lets the decal expire.
        </p>
        <p><br />
            In order to move our group of selected units together we'll have to update our <strong>serverCmdmovePlayer()</strong> function to 
            tell all of our units where to go.
        </p>
function serverCmdmovePlayer(%client, %pos, %start, %ray)
{
    //echo(" -- " @ %client @ ":" @ %client.player @ " moving");

    // Get access to the AI player we control
    %ai = findTeam1Leader();

    %ray = VectorScale(%ray, 1000);
    %end = VectorAdd(%start, %ray);

    // only care about terrain objects
    %searchMasks = $TypeMasks::TerrainObjectType | $TypeMasks::StaticTSObjectType | 
    $TypeMasks::InteriorObjectType | $TypeMasks::ShapeBaseObjectType | 
    $TypeMasks::StaticObjectType;

    // search!
    %scanTarg = ContainerRayCast( %start, %end, %searchMasks);

    // If the terrain object was found in the scan
    if( %scanTarg )
    {
        %pos = getWords(%scanTarg, 1, 3);
        // Get the normal of the location we clicked on
        %norm = getWords(%scanTarg, 4, 6);

        // Set the destination for the AI player to
        // make him move
        if (isObject(Team1List))
        {
            %c = 0;
            %end = Team1List.getCount();
            %unit = Team1List.getObject(0);
            while (isObject(%unit))
            {
                if (%unit.isSelected)
                {
                    %dest = VectorSub(%pos, %unit.destOffset);
                    %unit.setMoveDestination( %dest );
                }
                %c++;
                if (%c < %end)
                    %unit = Team1List.getObject(%c);
                else
                    %unit = 0;
            }
        }
        else
            %ai.setMoveDestination( %pos );
    }
}
        <p><br />
            
            Now we have to modify <strong>scripts/player/default.bind.cs</strong> to add some new functions 
            and a new bind right after our bind to spawn enemy targets.
        </p>
function addSelect()
{
    $SelectToggled = true;
    commandToServer('toggleMultiSelect', true);
}

function dropSelect()
{
    $SelectToggled = false;
    commandToServer('toggleMultiSelect', false);
}

moveMap.bindCmd( keyboard, "ctrl x", "addSelect();", "dropSelect();" );
        <p>
            Now we have <strong>ctrl-X</strong> bound to tell our system to toggle multi-selection
            via the <strong>addSelect()</strong> and <strong>dropSelect()</strong> functions 
            on make and break respectively.&nbsp; This key combination was chosen 
            arbitrarily and you can of course use any key you like.&nbsp; Note that at the 
            moment <strong>shift</strong> only catches the &quot;make&quot; (in other words, it only 
            catches the event when you press the key down) and not the &quot;break,&quot; so if&nbsp; 
            you use it you&#39;ll have to write the function to toggle between multi-selection 
            and single selection when shift is pressed.</p>
              <p>
                  If you test things now you should be able to select multiple units after you 
                  have spawned them and right-click to send them all off together.&nbsp; Note that 
                  you will need to click somewhere very near the units&#39; pelvis node to actually 
                  select them.</p>
              <p><br />
                  <img alt="" src="images/RTS_MultiSelectMoving.png" /></p>
              <p><br />
                  If you use the &#39;b&#39; key to spawn a target and then left-click on it while 
                  multiple units are selected they will all attack the target.&nbsp; You will need 
                  to left-click the terrain to stop them from attacking.&nbsp; Left-clicking the 
                  terrain will also clear your current selection group.</p>
              <p><br />
                  <img alt="" src="images/RTS_MultiSelectAttacking.png" /></p>
              Now open <strong>scripts/server/player.cs</strong>, find <strong>Armor::onDisabled()</strong> and 
                  add the following code after the call to <strong>%obj.playDeathAnimation()</strong>:</p>
   for (%i = 0; %i < Team1List.getCount(); %i++)
   {
       %unit = Team1List.getObject(%i);
       if (!isObject(%obj))
       {
           %unit.target = "";
           %unit.setAimObject(0);
           %unit.schedule(150, "setImageTrigger", 0, 0);
       }
   }
        <p>This will search our Team1List and stop any units who are currently attacking %obj (the dying object) to stop when
        %obj dies.</p>

        <p><br />
            That about wraps it up.  You should now have a pretty functional RTS prototype with unit control, unit spawning and some 
            other basic features that are typical of the genre.
        </p>

Conclusion

The purpose of this tutorial was to show you some of the more advanced capabilities of TorqueScript, and combine the language with Torque 3D's visual editors to create a prototype game. As you just experienced, getting a non-FPS prototype game started does not take long.


Make sure you have read through all the comments accompanying the new code, as they are part of the tutorial. At this point you can move on to other tutorials, or improve upon the code to create something more unique. There is always room for improvement, such as:

  • Changing the units' weapons out for rocket launchers or grenades
  • Make the targets move around and attack the player or the players units
  • Add key bindings to change camera modes on the fly

You can download the completed scripts by CLICKING HERE.

If you wish to download the scripts and assets in a single file, CLICK HERE.


A special thanks to Steve Acaster and his Tactics-Action Hybrid Game Tutorial series for saving me considerable time fiddling with the camera.

            </td>
        </tr>
      </tbody>
    </table>
<script type="text/javascript">

var links = document.getElementsByTagName('a');

for (var i = 0; i < links.length; i++) if (links[i].className == 'livethumbnail') { var img = links[i].getElementsByTagName('img')[0]; img.state = 'small'; img.smallSrc = img.getAttribute('src'); img.smallWidth = parseInt(img.getAttribute('width')); img.smallHeight = parseInt(img.getAttribute('height')); img.largeSrc = links[i].getAttribute('href'); img.largeWidth = parseInt(img.getAttribute('largewidth')); img.largeHeight = parseInt(img.getAttribute('largeheight')); img.ratio = img.smallHeight / img.smallWidth; links[i].onclick = scale; }

function scale() { var img = this.getElementsByTagName('img')[0]; img.src = img.smallSrc;

if (! img.preloaded)
{
	img.preloaded = new Image();
	img.preloaded.src = img.largeSrc;
}

var interval = window.setInterval(scaleStep, 10);
return false;

function scaleStep()
{
	var step = 45;
	var width = parseInt(img.getAttribute('width'));
	var height = parseInt(img.getAttribute('height'));
	
	if (img.state == 'small')
	{
		width += step;
		height += Math.floor(step * img.ratio);
		
		img.setAttribute('width', width);
		img.setAttribute('height', height);
		
		if (width > img.largeWidth - step)
		{
			img.setAttribute('width', img.largeWidth);
			img.setAttribute('height', img.largeHeight);
			img.setAttribute('src', img.largeSrc);
			window.clearInterval(interval);
			img.state = 'large';
		}
	}
	else
	{
		width -= step;
		height -= Math.floor(step * img.ratio);

		img.setAttribute('width', width);
		img.setAttribute('height', height);
		
		if (width < img.smallWidth + step)
		{
			img.setAttribute('width', img.smallWidth);
			img.setAttribute('height', img.smallHeight);
			img.src = img.smallSrc;
			window.clearInterval(interval);
			img.state = 'small';
		}
	}
}			

}

</script>
Clone this wiki locally