Search code examples
math2dcollision-detection

2D Continuous Collision Detection


I'm trying to implement simple continuous collision detection for my pong game however i'm not sure i'm implementing or understand this right. AFAIR continuous collision detection is used for fast moving objects that may pass through another object circumventing normal collision detection.

So what I tried was that because the only fast moving object I have is a ball I would just need the position of the ball, its move speed, and the position of the object we are comparing to.

From this I figured it would be best that for example if the ball's move speed indicated it was moving left, I would compare it's left-most bound to the right-most bound of the other object. From this I would step through by adding the move speed to the left-most bound of the ball and compare to make sure it's greater than the other objects right bound. This would show that there is no left right collision.

I have something somewhat working, but unfortunately, the ball starts bouncing normally for a while then it acts as if it hits a paddle when nothing is there.

I'm a bit lost, any help would be appreciated!

static bool CheckContinuousCollision(PActor ball, PRect ballRect, PActor other, PRect otherRect)
{
    PVector ballMoveSpeed;
    int ballXLimit;
    int ballYLimit;

    ballMoveSpeed = ball.moveSpeed;

    // We are moving left
    if ( sgn(ball.moveSpeed.x) < 0 )
    {
        ballXLimit = std.math.abs(ballMoveSpeed.x) / 2;

        for ( int i = 0; i <= ballXLimit; i++ )
        {

                if ( ballRect.Left < otherRect.Right && otherRect.Left < ballRect.Left)
            {
                return true;
            }

            ballRect.Left -= i;
        }
    }

            //We are moving right
    if ( sgn(ball.moveSpeed.x) > 0)
    {
        ballXLimit = std.math.abs(ballMoveSpeed.x) / 2;

        for ( int i = 0; i < ballXLimit; i ++ )
        {

            if ( ballRect.Right > otherRect.Left && ballRect.Right < otherRect.Right )
            {
                return true;
            }   

            ballRect.Right += i;
        }
    }
            // we are not moving
    if ( sgn(ball.moveSpeed.x) == 0)
    {
        return false;
    }
}

Solution

  • You seem to be checking the collision of only one dimension, i.e the X dimension of your ball versus your Other.

    What you probably want is to compare whether the two objects collide in 2d space. This can be easily done by adjusting each objects Bounding Rectangle and checking whether the rectangles overlap. Then in your for loop you can adjust your Ball rectangle accordingly