Feel free to send me an e-mail. If you do, be sure to include an email so that I can get back to you
Break-away Clone
This is a game where you move a pedal and try to hit the ball to break the blocks. As you break the blocks you accumulate points. The graphics are done using OpenGL.
How did I handle collision?
I used bounding rectangles around the various sprites, and then I checked whether another object penetrated its boundaries. If its borders were penetrated, I then moved the object outside of its bounding rectangle and negated the velocity component that was perpendicular to the edge. The Four Collision Constraints (Assuming its position is denoted by bottom-left corner):
- Object1.x < Object2.x (From the left)
- Object1.x > Object2.x + Object2.width (From the right)
- Object1.y < Object2.y + Object2.height and Object1.y > Object2.y (From the bottom)
- Object1.y > Object2.y + Object2.height and Object1.y > Object2.y (From the top)
Use those constraints to bound objects by a rectangle.
Collision Handling
// Check for wall collision
if(ball->x > Wall.x + Wall.width)
{
ball->x = Wall.x + Wall.width;
ball->NegateXVelocity();
}
else if(ball->x < Wall.x)
{
ball->x = Wall.x;
ball->NegateXVelocity();
}
else if( ball->y > Wall.y + Wall.height )
{
ball->y = Wall.y + Wall.height;
ball->NegateYVelocity();
} else if(ball->y < Wall.y)
{
ball->y = Wall.y;
ball->NegateYVelocity();
}
// Check for Collison with Ball and UserBlock
if(Sprite_Collide(ball, User_Block) == TRUE )
{
// from the left
if(ball->x < User_Block->x)
{
ball->x = User_Block->x;
ball->NegateXVelocity();
}
// from the right
else if(ball->x > User_Block->x + User_Block->width)
{
ball->x = User_Block->x + User_Block->width;
ball->NegateXVelocity();
}
// from the top
else if( ball->y < User_Block->y + User_Block->height && ball->y > User_Block->y )
{
ball->y = User_Block->y + User_Block->height;
ball->NegateYVelocity();
}
// from the bottom
else
{
ball->y = User_Block->y - ball->height;
ball->NegateYVelocity();
}
}
By the way, this is a great example of how not to do things. For example, if you could change the Sprite_Collide() function to take a callback to handle the collision than you can essentially do everything in one pass for the ball and UserBlock collision.
Comments