Search Unity

Question Draw a line touching to the circumference of a circle

Discussion in '2D' started by hgokturk, Mar 31, 2023.

  1. hgokturk

    hgokturk

    Joined:
    Jun 29, 2016
    Posts:
    17

    Hi,
    Say the circle is at (3, 3). How to calculate the vector position of the arrow line?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    If the vector always hits the circle at 90 degrees then it is just Pythagoras for the diagonal minus the radius of the circle.
     
  3. hgokturk

    hgokturk

    Joined:
    Jun 29, 2016
    Posts:
    17
    Code (CSharp):
    1. line.SetPosition(0, new Vector3(0, 0, 1));
    2. line.SetPosition(1, new Vector3(x, y, 1));
    So if the radius is 0.5 then
    Code (CSharp):
    1. line.SetPosition(0, new Vector3(0, 0, 1));
    2. line.SetPosition(1, new Vector3(x - 0.5f, y - 0.5f, 1));
    ?

    Unfortunately this is not working and probably I'm missing something here. Thanks for replying.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    You've left poor Mr Pythagoras out in the cold!

    He's the one that tells us that the length of the hypotenuse of a right triangle is given by the square root of the sum of the squares of each side, to wit:

    Code (csharp):
    1. float len = Mathf.Sqrt( x * x + y * y);
    So that's the linear distance from (0,0) to the center of the circle.

    You could save some time by putting x/y into a Vector2, like-a-so:

    Code (csharp):
    1. Vector2 temp = new Vector2( x, y);
    2.  
    3. float distance = temp.magnitude; // <--- pythagoras magic done for us by the math library here
    4.  
    5. Vector2 tipOfArrow = temp.normalized * (distance - circleRadius);
    Presto! As I said, Pythagoras minus the radius.
     
    hgokturk and MelvMay like this.
  5. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,492
    As above. What you were defining was touching a Box not a Circle if you think about it logically.
     
    hgokturk likes this.