[Tutorial]Pong Part 2

Welcome to the second part of my pong tutorial. Today we will work on making the ball bounce around the screen. If you dont have the project files from the last tutorial, you can download them here. Ok, now that your ready, lets get started. So in the previous tutorial, we just drew the ball at the coordinates (0,0). But now we want to make the ball move. To do that we can make a ball struct:

typedef struct {
float Pos, Old;
} Ball;

So to use this, we need to declare an instance of our ball. Lets call it myBall.

Ball myBall;

So now that we have our own ball, lets set its position to zero in the same place that we init the graphics:

myBall.Pos.x = 0;
myBall.Pos.y = 0;
myBall.Old.x = 0;
myBall.Old.y = 0;

So now that we have set the balls position, lets update the drawing code to draw the sprite where the ball is:

[sprBall renderAtPoint:CGPointMake(myBall.Pos.x,myBall.Pos.y) centerOfImage:YES];

Now that we have all the drawing code out of the way, we can work on moving the ball. To handle the ball physics, we will use simple verlet integration. Basically we find the velocity of the ball by subtracting the old position form the new position. Then we move the ball according to the velocity.

float xVel = myBall.Pos.x - myBall.Old.x;
float yVel = myBall.Pos.y - myBall.Old.y;
myBall.Old.x = myBall.Pos.x;
myBall.Old.y = myBall.Pos.y;
myBall.Pos.x += xVel;
myBall.Pos.y += yVel;

Ok, so now if we run that, you’ll find that the ball isn’t moving! In order to make it move, we need to change the old position of the ball. Lets set myBall.Old.x and myBall.Old.y to 1.

After you’ve done that, you will see your ball move to the upper left! Thats it for this tutorial, in the next tutorial we will work on making the ball bounce off the walls.

~ by admin on August 29, 2009.

Leave a Reply