Search Unity

RayCast hit movement Object ?

Discussion in 'Scripting' started by Quast, Dec 30, 2018.

  1. Quast

    Quast

    Joined:
    Jul 5, 2015
    Posts:
    560
    Hi.
    There is a part in my script where I need to make a ray from my mussel to enemy. This enemy could be anywhere around player. I found my ray is not moving to target position !.

    Code (CSharp):
    1.   public Transform target,Bullet_position;
    2.  
    3. void Update {
    4.  
    5.         if (target != null)
    6.         {
    7.             RaycastHit hit;
    8.             if (Physics.Raycast(Bullet_position.position, target.position, out hit, 500))
    9.             {
    10.                 Debug.DrawRay(Bullet_position.position, target.position, Color.blue, 500);
    11.  
    12.                 if (hit.collider.tag == "enemy")
    13.                 {
    14.                     print(" In Range and i can see you! ");
    15.                 }
    16.                 else
    17.                 {
    18.                     print(" None!! ");
    19.                 }
    20.             }
    21.         }
    22.         else
    23.         {
    24.  
    25.         }
    26.                
    27.             }
     
  2. Zavalichi

    Zavalichi

    Joined:
    Oct 13, 2018
    Posts:
    162
    I think you have to calibrate your raycast:
    -set the position
    -when you move/rotate your player make sure that the position of raycast follow the player

    Code (CSharp):
    1.  
    2. public Vector3 frontSensorsPosition0 = new Vector3(0f, 0.5f, 0.1f); // we can change it at runtime
    3. public Transform target;
    4.  
    5. Vector3 startPosition = transform.position;
    6. startPosition += transform.forward * frontPosition.z; // for same direction
    7. startPosition += transform.up * frontPosition.y; // keep the height
    8.  
    9. if (Physics.Raycast(startPosition, transform.forward, out hit, 500))
    10.        if (hit.collider.CompareTag("player"))
    11.               Debug.log("I can see you!");
    12.  
    Add the script to bullet.
     
  3. coppertones

    coppertones

    Joined:
    Mar 31, 2018
    Posts:
    16
    The Raycast function uses the second vector as a direction from the origin, ie. if it's
    Vector3.down
    , it will tell you if there's ground below you. Replace
    target.position
    with
    target.position - Bullet_position.position
    in your raycast function.