Search Unity

Resolved (Geometry) Length of a line where it goes through a circle.

Discussion in 'Scripting' started by INeatFreak, Aug 12, 2019.

  1. INeatFreak

    INeatFreak

    Joined:
    Sep 12, 2018
    Posts:
    46
    hi. i need to find length of a line where goes through a circle with radius 690 meters. look at the picture to better understand what am i asking. thanks.
    circle.PNG

    or how can i calculate distance from green sphere to point where line intersects with edge of purple circle.
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Alright, let's dust off some high school algebra! The two important input numbers are: how far from the circle's center is the line (d), and how big is the circle's radius (r)? I see 690 here for the latter, and the former could be found with something like this sample code.

    Obviously, if d > r, return 0. If d == 0, return r * 2. All other answers will be in between.

    When you have the line reduced to "distance from the circle center", you can picture the problem as a horizontal line a=d units above the origin, so its formula is a simple y = d. If you can find the appropriate X where this line intersects the circle, you can multiply that by 2 and there's your length. The circle's formula is x^2 + y^2 = r^2.

    So now you can just sort of mash the line's formula in with the circle's formula and solve for x.

    x^2 + y^2 = r^2
    y = d
    x^2 + d^2 = r^2
    x^2 = r^2 - d^2
    x = sqrt(r^2 - d^2)

    Multiply by 2 and there's your formula. Set r to 690 and d to your line's distance and you should get the right answer. Or in code form:
    Code (csharp):
    1. float GetDistWithinCircle(float lineDistToCircleCenter, float circleRadius) {
    2. if (lineDistToCircleCenter >= circleRadius) return 0f; //if we don't do this one special we'll be taking sqrt of a negative number below
    3. return 2f * Mathf.Sqrt(circleRadius * circleRadius - lineDistToCircleCenter * lineDistToCircleCenter);
     
    INeatFreak and lordofduct like this.