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. Dismiss Notice

Question Check if GameObject is x units next to GameObject2

Discussion in 'Scripting' started by qflvty, Jan 17, 2021.

  1. qflvty

    qflvty

    Joined:
    Jan 13, 2021
    Posts:
    5
    Please, help needed...
    Like in title: I want to check is there GameObject X units away from another GameObject
    For example
    If there is GameObject 10 units away from GameObject2 in X axis, do something.

    Thanks for any help in this topic.
     
  2. JoshWindsor

    JoshWindsor

    Joined:
    Jun 2, 2018
    Posts:
    24
    Code (CSharp):
    1.     float distance = Vector3.Distance (object1.transform.position, object2.transform.position);
    2.  
    https://docs.unity3d.com/ScriptReference/Vector3.Distance.html

    Perhaps you will have to define the size of a unit as a float and then you can figure the total distance? Not entirely sure how you'd go about this if only moving at right angles?
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,756
    What Josh says is right on but keep in mind you cannot compare floating point values for equality due to floating point imprecision.

    Instead it is always best to compare for crossing that distance by keeping the previous distance from the previous frame and comparing it to this one.
     
    JoshWindsor likes this.