Jump to content
  • Advertisement
Sign in to follow this  
h3ro

Question about finit line and circle intersection

This topic is 3567 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!