Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Finding Magnitudes of 2 different vectors

Discussion in 'Scripting' started by KushMathur, Aug 15, 2019.

  1. KushMathur

    KushMathur

    Joined:
    Jul 3, 2019
    Posts:
    22
    Hey Team!
    vector3.magnitude is used to find magnitude of vector from origin. But in my case, I need to find the magnitude between 2 vectors.

    Should I separate them to their components and then apply math functions to calculate or do we have a special function to do it.

    I am fairly new to Unity, thanks for understanding!:)

    Thanks!
     
  2. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,745
    It has no matter with unity, basic geometry. You want (To - From).magnitude
     
  3. KushMathur

    KushMathur

    Joined:
    Jul 3, 2019
    Posts:
    22
    Thanks for replying, but Vector3.magnitude doesn't give output when provided with 2 vectors. Or did I understood it in a wrong way?
     
  4. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,385
    You have to subtract the 2 vectors, which results in a new vector, and you get the magnitude of the new vector.

    Code (csharp):
    1. float distBetweenAB = (b - a).magnitude;
    Exactly the code palex-nx showed.

    There is also Vector3.Distance:
    https://docs.unity3d.com/ScriptReference/Vector3.Distance.html

    Code (csharp):
    1. float distBetweenAB = Vector3.Distance(a, b);
    Though really it just effectively does the same thing underneath (just vector component wise).
    https://github.com/Unity-Technologi...ob/master/Runtime/Export/Math/Vector3.cs#L321
     
    KushMathur and palex-nx like this.
  5. KushMathur

    KushMathur

    Joined:
    Jul 3, 2019
    Posts:
    22
    That worked out, thanks a lot!