Enemy always to look and shoot in direction of player

I have a few issues with this, I have tried, and searched and searched but maybe I’m misunderstanding it completely. This is what I have so far:

if (Alive && !Flinching) {
       transform.LookAt(Player);
}

This is in FixedUpdate(), then I call the Shoot method which runs every couple of seconds, like this:

void Shoot(){
        Vector3 fwd = transform.TransformDirection(transform.forward);
        GameObject clone = Instantiate(bullet, transform.position, Quaternion.identity) as GameObject;
        clone.transform.rotation = Quaternion.LookRotation(fwd);
        clone.GetComponent<Rigidbody>().AddRelativeForce(Vector3.Normalize(fwd) * 15, ForceMode.Impulse);
}

But even though the enemy is looking directly at the player, the bullet (laser) is missing the player by some distance. And the player isn’t even moving… if I move the player a little bit it still misses by the same amount so why is it always missing :frowning:

Any help is appreciated

transform.forward is in world space already… you don’t need to convert it into world space coordinates

Thanks for your quick reply! Ah, so once again I was over complicating things =( I changed it to this:

GameObject clone = Instantiate(bullet, transform.position, Quaternion.identity) as GameObject;
clone.GetComponent<Rigidbody>().AddRelativeForce(Vector3.Normalize(transform.forward) * 15, ForceMode.Impulse);

And it now shoots it at the player, thank you very much :slight_smile:

local axis in world space, confused me too :smile:

Quick question while I’m here, the bullet is just a capsule object, so I need it to be 90f on the Z rotation. But how do I point the bullet in the same direction of the player, or whatever direction the turret is facing. I have tried a few things but all this Quaternion business is really confusing me :frowning:

I have tried using the transform.Rotate() method, also the rotation x y z but to no avail :frowning:

Quaternion.identity is just “face north” (or whatever direction the vector3(0,0,0) is called), if you want the clone bullet to point the same direction as the transform this script is attached to is you can pass in it’s rotation instead.

GameObject clone = Instantiate(bullet, transform.position, transform.rotation) as GameObject;

quaternion is just a fancy way of storing a rotation so that it doesn’t suffer from gimbal lock (i.e. look up, turn left => spin not turn), if you need to manipulate one you will pretty much always need to convert it into a euler representation (x, y, z), do what is need and convert it back.