Alright, so I’m trying to move a ball to it’s closest location along a line that it hits. But my dist.y is saying it’s extremely far away even when I’m right next to the line. Can anyone tell me whats going on?
Here is the code:
public Vector2f LineVsCircleCollision(Vector2f lineA, Vector2f lineB, Vector2f circle, float rad)
{
Vector2f line = new Vector2f(0,0); // the line vector
Vector2f.sub(lineB, lineA, line);
Vector2f circ = new Vector2f(0,0); // the vector of the origin line point to the circle center
Vector2f.sub(circle, lineA, circ);
// project the circle vector onto the line vector
float proj = Vector2f.dot(line,circ) / Vector2f.dot(line,line);
if(proj < 0) proj = 0;
else if(proj > 1) proj = 1;
// apply the projected position to our vector, and offset it by our origin
Vector2f nearest = new Vector2f(0,0);
line.scale(proj);
Vector2f.add(line, lineA, nearest);
// 'nearest' is now the point on the line nearest the circle
// see if the distance between this point and the circle center is greater than the radius.
// if the radius is larger, the circle intersects
Vector2f dist = new Vector2f(0,0);
Vector2f.sub(circle, nearest, dist); // the vector between the circle and the nearest point on the line
System.out.println("hit: " + (Vector2f.dot(dist,dist) <= (rad*rad)));
System.out.println("x: " + dist.x + " y: " + dist.y);
return dist;
}