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
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Question about distance between 2 objects

Discussion in 'Scripting' started by mk1978, Jul 31, 2010.

  1. mk1978

    mk1978

    Joined:
    Dec 27, 2009
    Posts:
    276
    This is pretty much newbie question.

    I am measuring the distance between two objects with the script below. Anyway, how can I measure the distance only in the x and z axis? Basically, I would like to omit the altitude of objects when measuring the distance between them. Is there any simple way to do this?

    Code (csharp):
    1. var distance: float;
    2. var A : GameObject;
    3. var B : GameObject;
    4.  
    5. function Update () {
    6.  
    7. // calculate distance between A and B
    8.    
    9. distance = Vector3.Distance(A.transform.position, B.transform.position);
    10.        
    11. }
     
  2. menneske

    menneske

    Joined:
    Jan 23, 2009
    Posts:
    44
    Code (csharp):
    1.  
    2. Vector3 p1 = A.transform.position;
    3. Vector3 p2 = B.transform.position;
    4. p1.y = p2.y;
    5.  
    6. distance = (p1-p2).magnitude;
    7.  
     
  3. mk1978

    mk1978

    Joined:
    Dec 27, 2009
    Posts:
    276
    Thanks for offering to help me menneske! Anyway, I ran to some problems when testing the script. Below is the script like I have it right now. Do you have idea what is causing the problem?

    According to Unity:
    Assets/Scripts/NewBehaviourScript.js(9,8 ): UCE0001: ';' expected. Insert a semicolon at the end.

    I inserted the semicolons but then Unity claims:
    Assets/Scripts/NewBehaviourScript.js(9,1): BCE0034: Expressions in statements must only be executed for their side-effects.

    Code (csharp):
    1. var distance: float;
    2. var A : GameObject;
    3. var B : GameObject;
    4.  
    5. function Update () {
    6.  
    7. // calculate distance between A and B
    8.    
    9. Vector3 p1 = A.transform.position;
    10. Vector3 p2 = B.transform.position;
    11. p1.y = p2.y;
    12.  
    13. distance = (p1-p2).magnitude;
    14.        
    15. }
     
  4. menneske

    menneske

    Joined:
    Jan 23, 2009
    Posts:
    44
    Yeah, sorry, the code I posted is C#, not JavaScript. The javascript would look like this:
    Code (csharp):
    1.  
    2. var p1 : Vector3 = A.transform.position;
    3. var p2 : Vector3 = B.transform.position;
    4. p1.y = p2.y;
    5.  
    6. distance = (p1-p2).magnitude;
    7.  
     
  5. mk1978

    mk1978

    Joined:
    Dec 27, 2009
    Posts:
    276
    Thanks again!