# How To Resolve Collision Before it Occurs

I have 2 objects, A and B, in a 2 dimensional space. If I know A is trying to move by vector M (that is to add vector M to the positional vector of A), and that A will collide with B after A moves, what math would be used to scale back the M's x and y components such that M will no longer collide, whilst still allowing M to make A slide along B should x or y be cut back? (eg. if A is on the left of B, moves with vector (1f,1f), cant move 1 right, but can move 1 up and does so).

• Try vector projection desmos.com/calculator/8gyv18tghu – Ocelot Sep 5 at 10:11
• ^ this ended up being my solution, with a little bit of tinkering. Can't choose a comment as a solution though – PoisonedPorkchop Sep 6 at 9:04

Try vector projection as illustrated here

Vector projection formula:

$$(\vec{a}\cdot\hat{\vec{b}})\times\hat{\vec{b}}$$

where b with a hat means norm of the vector

$$\hat{\vec{b}} = \frac{\vec{b}}{\left\|\vec{b}\right\|}$$

You can represent side of object B and velocity of object A as vectors and use vector projection to remove any velocity directed at object B allowing A to slide across it. • This is currently a link-only answer. It may be more helpful to future readers, and more robust against link rot, if you edit your answer to include at least a rough overview of how to apply the math demonstrated at this link to solve this problem. – DMGregory Sep 6 at 10:53
• @DMGregory you mean vector projection formula? It's trivial, but OK. – Ocelot Sep 6 at 11:11
• It's trivial, but still news to a lot of our users! And having it is better than not having it, if the link ever breaks. Even better (and more upvote-attracting) if you include a step-by-step guide to how to use vector projection to stop before a collision, as asked above. – DMGregory Sep 6 at 11:14
• @DMGregory is it any better? That's all what I can do. – Ocelot Sep 6 at 13:04
• I'd say this is much better, thank you for taking the time to expand on it! – DMGregory Sep 6 at 13:08

I would rather be able to comment, since you are missing a lot of information, but since I cannot I will post a possible solution.

Using circle/circle collision detection:

Before each move, add M temporarily to A's position. Then calculate the distance between A's new position and B. If that distance is less than the radius of A's bounding circle added to the radius of B's bounding circle, then you need to scale back M, by the difference plus some constant value (if you don't add this constant value, then the two objects will collide, but just barely touch).

Your bounding circles can be arbitrary also, since you are trying to avoid collisions. You can make them much larger than the objects themselves.

Hope this helps!