Torque2D/pong Tutorial TGB Player Setup

From TDN

This page is a Work In Progress.

Contents


Create the Player



This is the function to create the player. More to come on it later.

// create the player
function createPlayer()
{
   $player = new t2dStaticSprite() { scenegraph = t2dscene; };
   $player.setImageMap(paddleImageMap);
   $player.setSize($paddleSize);
   
   $player.setCollisionActive(true, true);
   $player.setCollisionPhysics(true, true);
   $player.setCollisionResponse(CLAMP);
   $player.setCollisionCallBack(true);
   $player.setLayer($paddleLayer);
   $player.setGraphGroup($paddleGroup);
   $player.setCollisionMasks (BIT($arenaGroup), BIT($arenaLayer));
   
   // Attributes
   $player.moveSpeed = $paddleSpeed;
}



Ok, let's add a resetPlayer function to player.cs.

function resetPlayer(%pos)
{
   $player.setPosition(%pos);
}


Bind some keys


Here is my defaultBind.cs. I will explain more later

// Globals
GlobalActionMap.bindCmd(keyboard, "escape", "", "quit();");
GlobalActionMap.bindCmd(keyboard, "Ctrl o", "", "Canvas.PushDialog(OptionsDLG);");


new ActionMap(moveMap);

moveMap.bind(keyboard, up, "moveUp");
moveMap.bind(keyboard, down, "moveDown");
moveMap.bind(keyboard, "/", "multiball");
moveMap.push();

// moveMap Functions

function moveUp(%val)
{
   $moveUp = %val;
}

function moveDown(%val)
{
   $moveDown = %val;
}

function multiball(%val)
{
   if (%val)
   {
      launchBall();
      launchBall();
      launchBall();
      launchBall();
   }
}







Move the paddle

Now this is the move function that goes in Player.cs

function movePaddle()
{  
   if ( isObject($player) )
   {
      %moveY = $moveDown - $moveUp;
      $player.setLinearVelocity(0, %moveY * $player.MoveSpeed);
   }
}


This function will check the triggers and call the movePaddle() function on every frame update. It should be placed in ./game.cs.

function t2dSceneGraph::onUpdateScene(%this)
{
   if (%this != t2dscene.getID())
      return;
   movePaddle();
   
   // check the triggers
   for (%i = 0; %i < TriggerCheckGroup.getCount(); %i++)
         checkTrigger(TriggerCheckGroup.getObject(%i));   
}


Back - The Paddles | Overview | Next - Setting up the blips