Enemy raycast shooting not working

I am working on creating the shooting function of a sentry gun, but when I play the game the ray does not work properly, it just points in the same direction no matter where the sentry is pointing.
Here is the code:

function LookAt ()
{
// changes the rotation of the sentry based on the rotation of the sentry gun based on where the player (target) is
    var rotation = Quaternion.LookRotation(target.position - transform.position);
    transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * turnSpeed);
}

function Attack ()
{

    var hit : RaycastHit;
    var ray = transform.TransformDirection(transform.forward);
  
  
    if (Physics.Raycast (transform.position, ray, hit, 100))
    {
       // if the ray hits the player, then it will tell me for now, later I will make it damage the player
       if (hit.collider.gameObject.tag == "Player")
       {
           Debug.Log("The player was hit");
        }
    }
}

I tried to make comments so that you could see what things were supposed to do. Can anybody see an error in my script? There are no compiler errors, but the script doesn’t work like I want it to.
Thanks for your help

try drawing your ray using

 Debug.DrawRay(transform.position,ray, Color.red);

and see where it is pointing at.
I have a feeling that transform.forward is not the right direction in your case.

I created the DrayRay statement, and it does point in the correct direction, but the function apply damage is not being called, I guess that there must be a problem in the apply damage.

Maybe the actual collider that you are hitting isn’t the one that has the ‘player’ tag set? Output your hit.collider.gameObject.name and see what it’s hitting.

(Note that raycasts do hit trigger colliders as well)

1 Like

Thank you for your help, I just realized that the shooting was hitting the enemy’s collider. Thank you, I’ll just tell it to ignore that collider.