Physics.Raycast not working as expected!

Hi! :slight_smile:
I am trying to make my moving capsule to stop when it detects the object tagged “Finish” coming in front of it by using a raycast to detected and check for coming object within distance specified in “sensDistance”, but the capsule keep going like the raycast is not working or something, i really couldn’t figure out the problem and i dont know if i am missing something about raycasts. this is my piece of code and please help ASAP:

public float speed = 110f;
bool front;
float sensDistance = 3f;
RaycastHit frontHit;
Ray forwardRay;
float sensDistance = 3f;


void Start() {
forwardRay = new Ray(transform.position,transform.TransformDirection(Vector3.forward));
}

void Update() {
// 
     Debug.DrawRay(transform.position, forwardRay.direction * sensDistance, Color.red);

     front = Physics.Raycast (forwardRay, out frontHit, sensDistance);
//
     if (!front)
         Move (Vector3.forward, speed);
     else {
     if(frontHit.collider.tag == "Finish" )
         StopMove();
     }
}

void Move(Vector3 direction, float _speed) {
     rigidbody.velocity = transform.TransformDirection ((direction * _speed *  Time.deltaTime));
}

void StopMove() {
     rigidbody.velocity = Vector3.zero;
}

One potentially serious issue with your code is that you set the position and the direction for the Raycast() in Start(). That means it never changes even when the object moves or changes direction. There is a version of Raycast that takes a position and a direction, so you don’t need to construct a ray. So get rid of the ray, and do this for your Raycast():

 front = Physics.Raycast(transform.position, transform.forward, out frontHit, sensDistance); 

And your Debug.DrawRay() then becomes:

 Debug.DrawRay(transform.position, transform.forward * sensDistance, Color.red);