Search code examples
algorithmlinecollisiongeometryintersection

What could be wrong with my function for finding a solution for circle-line collision?


So I am working on a simple function in which you provide a single point and an angle along with the radius of the circle, the line intersects, and you get back one of the points of intersection. For some very unknown reason I am not getting the expected x position? My calculation for the x position is based on: http://mathworld.wolfram.com/Circle-LineIntersection.html

I would be very satisfied if any of you guys could do the same, but for your function to spit out the x position expected in this very case to be -27.386 for one solution and 27.386 for the other, according to the Desmos Graphing Calculator.

The point is (-70, -40.415), going at an an angle of PI/6 and the circle radius is sqrt(1000). Using this info, you should be able to get the two x solutions.

My code:

function sgn(x) {
    return x < 0 ? -1 : 1;
}

function findPointOfCollision(p, t, r) { // p -> point, t -> theta, r -> radius
    p2 = [p[0] + 200*Math.cos(t), p[1] + 200*Math.sin(t)]; // Another point in the line given by point and angle

    let x1 = p[0];
    let y1 = p[1];

    let x2 = p2[0];
    let y2 = p2[1];

    let dx = x2 - x1;
    let dy = y2 - y1;

    let dr = Math.sqrt(dx*dx + dy*dy);
    let D = x1*y2 - x2*y1;

    let x = (D*dy + sgn(dy)*dx*Math.sqrt(r*r*dr*dr - D*D))/dr*dr;

    return [x]; // Only need the x position for the collision point atm
}



function start () {
    console.log(findPointOfCollision([-70, -40.415], Math.PI/6, 31.6227766017));
}

Solution

  • Your algorithm is correct, but you have an error in the last formula when you divide by dr²: A/dr*dr means (A/dr)*dr, which effectively cancels out the division. You must place parentheses around the denominator here: A/(dr*dr).

    When I change the formula for x to:

        let x = (D*dy + sgn(dy)*dx*Math.sqrt(r*r*dr*dr - D*D)) / (dr*dr);
    

    I get the expected value of about 27.386.