I am trying to create a tank enemy in my game, and I want it to have a linear turret rotation speed, so I´m trying to calculate the relative rotation between the tank and it´s turret so I can make it point to it´s target ( the player )
below is the code I have:
void Update () {
// this is just a sample code to change the tank´s rotation so I can test the code
float s = Time.deltaTime * 10f;
this.transform.position += this.transform.forward * s; // this would make it move forward
this.transform.forward = Quaternion.AngleAxis( 45*Time.deltaTime, Vector3.up) * this.transform.forward; // this makes it rotate a little
Camera cam = Camera.mainCamera;
Vector3 dif = cam.transform.position - this.transform.position; // this will save a vector pointing to player
dif.Normalize(); // this is so that my vector would have the some length as the forward vector
dif = dif - this.transform.forward; // this is what I thought would work
float ay = Mathf.Atan2( dif.x, dif.z ) * 180f / Mathf.PI; // this code works fine if the tank is stopped
_turret.localEulerAngles = new Vector3( -90, ay, 0 );
}