Sign in to follow this  
h3ro

Question about finit line and circle intersection

Recommended Posts

h3ro    161
Hallo, I need to determine if a line intersects with a circle. Intersecting with a line is trivial, but I am having problems when trying to use a finite line. I do not need to find the intersection point. All I need is a Boolean result. Here is the code I am using now (for checking against an unlimited line). How would I go about changing it so it works with a finite line?
function lineCircleIntersection(line, circlePos, circleRadius)
{
  // Math link:
  // http://mathworld.wolfram.com/Circle-LineIntersection.html

  // Move the points so that the circle is at 0,0
  var startX = line.m_start.x - circlePos.x;
  var startY = line.m_start.y - circlePos.y;
  var endX   = line.m_end.x - circlePos.x;
  var endY   = line.m_end.y - circlePos.y;

  var dx = endX - startX;
  var dy = endY - startY
  
  var lineLeght = Math.sqrt (dx * dx + dy * dy);
  
  var D = (startX * endY) - (endX * startY);
  
  var result = (circleRadius * circleRadius) * (lineLeght * lineLeght) - (D * D) 
  
  if(result > 0)
    return true;
  else
    return false;
}

regards,

Share this post


Link to post
Share on other sites
h3ro    161
Found it out. Sorry for wasting peoples time.

Here is the code I used, hopefully it will come up if someone is searching for something similar.

function intersectCircleLineSegment(line, circlePos, circleRadius)
{
var dirVector = new vector2D(0,0);
dirVector.x = line.m_end.x - line.m_start.x;
dirVector.y = line.m_end.y - line.m_start.y;

var diffVector = new vector2D(0.0);
diffVector.x = circlePos.x - line.m_start.x;
diffVector.y = circlePos.y - line.m_start.y;

var t = Dot2D(diffVector,dirVector) / Dot2D(dirVector,dirVector);

if ( t < 0)
t = 0;
else if(t > 1)
t = 1;

var closest = new vector2D(0,0);
closest.x = line.m_start.x + (t * dirVector.x);
closest.y = line.m_start.y + (t * dirVector.y);

var d = new vector2D(0,0);
d.x = circlePos.x - closest.x;
d.y = circlePos.y - closest.y;

var distSqrt = Dot2D(d,d);

if(distSqrt<= circleRadius * circleRadius)
return true;
else
return false;
}


Regards,

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this