Simple collision detection for pong
- by Dave Voyles
I'm making a simple pong game, and things are great so far, but I have an odd bug which causes my ball (well, it's a box really) to get stuck on occasion when detecting collision against the ceiling or floor. It looks as though it is trying to update too frequently to get out of the collision check.
Basically the box slides against the top or bottom of the screen from one paddle to the other, and quickly bounces on and off the wall while doing so, but only bounces a few pixels from the wall.
What can I do to avoid this problem? It seems to occur at random. Below is my collision detection for the wall, as well as my update method for the ball.
public void UpdatePosition()
{
size.X = (int)position.X;
size.Y = (int)position.Y;
position.X += speed * (float)Math.Cos(direction);
position.Y += speed * (float)Math.Sin(direction);
CheckWallHit();
}
// Checks for collision with the ceiling or floor.
// 2*Math.pi = 360 degrees
// TODO: Change collision so that ball bounces from wall after getting caught
private void CheckWallHit()
{
while (direction > 2 * Math.PI)
{
direction -= 2 * Math.PI;
}
while (direction < 0)
{
direction += 2 * Math.PI;
}
if (position.Y <= 0 || (position.Y > resetPos.Y * 2 - size.Height))
{
direction = 2 * Math.PI - direction;
}
}