Torque2D/pong Tutorial TGB Ball Setup

From TDN

This page is a Work In Progress.

Contents


Create the Ball



Here is the function I use to create the ball. Most of this function was taken from a forum thread I can't remember where it is, when I find it I will post a link.

//create the ball
function createBall(%posX, %posY, %velX, %velY)
{
   %ball = new t2dStaticSprite() { scenegraph = t2dscene; };
   %ball.setImageMap(ballImageMap);
   %ball.setSize("1 1");
   %ball.setPosition(%posX, %posY);
   
   //Collisions
   %ball.setCollisionActive(true, true);
   %ball.setCollisionPhysics(true, true);
   %ball.setCollisionResponse(BOUNCE);
   %ball.setCollisionDetection(CIRCLE);
   %ball.setCollisionCallBack(true);
   
   %ball.setLayer($ballLayer);
   %ball.setGraphGroup($ballGroup);
   %ball.setCollisionMasks (BIT($arenaGroup)|BIT($paddleGroup)|BIT($ballGroup)|BIT($triggerGroup),
                            BIT($arenaLayer)|BIT($paddleLayer)|BIT($ballLayer));
   
   %ball.setLinearVelocity( %velX, %velY );
}



Here is the function for killing the ball.

function killBall(%srcObj)
{
   error("Ball Killed()");
   $ballsLeft-- ;
   %srcObj.safeDelete();
   lblBallsLeft.setValue("Turns left: " SPC $ballsLeft);
   
   if ($ballsLeft <= 0)
      gameOver();
   
   LaunchBall();
}



A function to launch the ball.

function launchBall()
{
   %posX = 0;
   %posY = getRandom(-25, 25);
      
   %velX = getRandom(20,40);
   %velY = getRandom(-25, 25);
   
   createBall(%posX, %posY, %velX, %velY);
}



This is a function I used to check the balls movement speed and angle. This was to ensure that the ball would never bounce near verticle or at a very slow speed.

function checkVelocity(%ball)
{
   %velY =%ball.getLinearVelocityY();
   
   if (%velY >= 0 && %velY <= 10 )
   {
      %ball.setLinearVelocityY(%velY+10);
      error("Positive value");
   }
   else if (%velY <= 0 && %velY >= -10)
   {
      %ball.setLinearVelocityY(%velY-10);
      error("Negative value");
   }
}


Back- The Blip | Overview | The next part not done yet.