Simple collision detection for pong

Posted by Dave Voyles on Game Development See other posts from Game Development or by Dave Voyles
Published on 2012-06-01T02:33:28Z Indexed on 2012/06/01 4:50 UTC
Read the original article Hit count: 274

Filed under:
|

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;
        }
    }

© Game Development or respective owner

Related posts about XNA

Related posts about c#