Search Unity

Position thing int front of the gameobject

Discussion in 'Scripting' started by herbie, Nov 10, 2017.

  1. herbie

    herbie

    Joined:
    Feb 11, 2012
    Posts:
    237
    Hi,

    In my game I detect if something is in front of the gameobject like this:
    Code (CSharp):
    1. void Update() {
    2.         Vector3 fwd = transform.TransformDirection(Vector3.forward);
    3.         if (Physics.Raycast(transform.position, fwd, 10))
    4.             print("There is something in front of the object!");
    5.        
    6.     }
    Is there a way to get the exact x-position of the thing that is in front of the gameobject?
    So when the thing is detected, the x-position of the thing is stored.
    (by the way, the position of the gameobject is not always the same when the detection takes place).
     
  2. Malleck666

    Malleck666

    Joined:
    Jan 9, 2015
    Posts:
    235
    If you add..
    Code (csharp):
    1.  
    2. Ray ray = new Ray(transform.position, fwd)
    3. RaycastHit hit;
    4.  
    ...and add it as a parameter...

    Code (csharp):
    1.  
    2. if(Physics.Raycast(ray, out hit, 10)
    3.  
    You will be able to get the gameobject like this...

    Code (csharp):
    1.  
    2. hit.collider.gameobject
    3.  
     
  3. herbie

    herbie

    Joined:
    Feb 11, 2012
    Posts:
    237
    That was easy. Thanks for reply!