Search code examples
collision-detection

How can I detect if a ball is moving away from a wall?


The balls are defined as a circles with a radius, a position and a velocity, which is a 2D vector. The walls are defined by a start point and end point.

I am able to detect the collision between the ball and the wall and know how to reflect it about the normal. However the same collision can be detected AGAIN and the change of direction is repeatedly flipped, meaning essentially the ball stops moving.

So really need a simple way to say that a ball is moving away from the line already so I can ignore any additional collisions.


Solution

  • You need to have a normal vector on the wall to know its orientation. Take a dot product between the ball velocity vector and the wall normal. If the result of the dot product is greater than zero, the ball is moving away from the wall. If it is zero, then the ball is moving parallel and if it is less than zero, then the ball is moving towards the wall.

    Additional explanation: 2010-08-29 18:17

    A question has come up about the case of when the wall supports collisions from both sides. To handle collisions properly, you have to answer two questions: which side of the wall is the ball currently on ('inside' or 'outside') and which way is it moving relative to the wall normal? How to determine the answer to the second question is answered above.

    To answer the question about whether the ball is 'inside' or 'outside' of the wall, you start by calculating the vector from the ball to the wall (a point on the wall - center of the ball). Take the dot product of that vector with the wall normal vector. If the result is less than zero then the ball is 'outside' the wall. Equal to zero is on the wall and greater than zero is 'inside' the wall.

    You then have the answer to your two questions. Is the ball currently 'inside' or 'outside' the wall and is it currently moving towards the 'inside' or 'outside' of the wall.