Search Unity

Comparison of two vectors

Discussion in 'Scripting' started by Kandrbol, Oct 23, 2018.

  1. Kandrbol

    Kandrbol

    Joined:
    Aug 15, 2018
    Posts:
    117
    Debug.Log Player1.transform.position is (69.7, 174.0 , 0)
    My desired vector from move Player1 is (69.7, 174.0, 0).

    But this no function !!

    if (Player3.transform.position == IWantPosition.Player3)
    {
    For controling function: Debug.Log(6);
    }

    How it solved ?
    Thanks.
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Vector3.ToString() truncates the floats to a single decimal digit, so when you do "Debug.Log(Player3.transform.position);" you are not seeing the exact value of that Vector3.

    Also, a Vector3 is made up of 3 floats, and you should never compare floats using ==

    You should check that your Vector3 (position) is within a specific range, not that it is exactly equal to another Vector3.

    There's probably a better way of writing it, but this is just off the top of my head and should work:

    Code (csharp):
    1. if ((Player3.transform.position.x > IWantPosition.Player3.x - 0.1f) && (Player3.transform.position.x < IWantPosition.Player3.x + 0.1f) && (Player3.transform.position.y > IWantPosition.Player3.y - 0.1f) && (Player3.transform.position.y < IWantPosition.Player3.y + 0.1f) && (Player3.transform.position.z > IWantPosition.Player3.z - 0.1f) && (Player3.transform.position.z < IWantPosition.Player3.z + 0.1f))
    2. {
    3.   //Player3 is in position
    4. }
    I wouldn't be surprised if there is some handy function that does the same thing as above but with having to write a lot less code, so hopefully someone else comes along and posts it.
     
    Last edited: Oct 23, 2018
    SparrowGS likes this.
  3. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    Unity overrides the == operator on Vector3 to mean approximate equality rather than exact equality, so using == on Vector3 is actually totally fine as long as you are OK using Unity's default threshold for how close they have to be in order to be "approximately equal" (0.00001).
     
  4. Kandrbol

    Kandrbol

    Joined:
    Aug 15, 2018
    Posts:
    117
    But it no function with ==. Now I use Mathf.Approximately , and thi function. How accuracy is this function?
     
  5. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    According to the documentation you just linked, Mathf.Approximately has an even tighter tolerance than Vector3 ==

    I haven't tested them empirically, though.
     
  6. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    ((Vector1 - Vector2).sqrMagnitude < .01f)
     
    Joe-Censored and Kandrbol like this.
  7. Kandrbol

    Kandrbol

    Joined:
    Aug 15, 2018
    Posts:
    117
    Thanks.