How do you determine whether a "ball" collised with a "wall" in 2D?
Let's define a basic universe for our ball and wall to live in. As well as the ball and wall themselves, of course.
class Wall {
constructor(x1,y1,x2,y2) {
Object.assign(this,{x1,y1,x2,y2});
}
}
class Ball {
constructor(x,y,r) {
Object.assign(this, {x,y,r});
}
}
function setup() {
setSize(600, 400);
}
function draw() {
clear(`white`);
}
It's a 2D animation, so we can just check and see if the bal overlaps the wall, and if it does, resolve that "collision". But if the ball is moving fast enough that at some frame it's on one side of the line, without overlapping, and then the next frame it's already on the other side of the line, without overlapping, we'll never register a collision that should have absolutely been caught.
The wall is a line, and the ball's path is a line, so we can do a line/line intersection test. Except we neeed to take the ball's radius into account - okay, easy enough, we'll offset the wall by the radius of the ball. Except now we're doing very much the wrong thing near the start and end of the wall...
Instead of finding the intersection between the ball and the wall, let's find out every point where the ball needs to be in order to count as "colliding with the wall". And t turns out finding all possible collisions is simply a matter of tracing the ball around our line and plotting where the center of the ball is: that gives us a new shape that we can use, with different "collision resolution rules" depending on where the ball is.