I’m sorry for this post, I know there are a lot more like it, but they are mostly old or talk about 2D Games and don’t seem to be working for me.
I have a turret that is supposed to look at the player (preferably delayed), the base is only supposed to rotate around the y axis, which works with
var newRotation = Quaternion.LookRotation(transform.position - player.position);//, Vector3.back);
newRotation.x = 0.0;
newRotation.z = 0.0;
transform.rotation = Quaternion.Lerp(transform.rotation, newRotation, Time.deltaTime * 8);
But if I get behind the tower, so it would have to rotate 180° the rotation get’s slow and is not accurate anymore.
And when I tried to address the mounted gun (child) with the same script except for lock in y and z it didn’t do at all what I planned. I never got Quanternions - even in the Blender animation system. I heard it’s to counter gimbal lock, but it seems to me, this is what’s happening to my guns right now.
Any input on a better way to do it or possible fixes isgreatly appreciated.
The newRotation is a quaternion, you cant just set its values like x, y, z. Its a four component vector with differtent operations.
Instead you should lock the vector transform.position - player.position and pass that to quaternion.
Isn’t that what I’m doing? Or did you mean for the child (guns)?
Anyways, I kinda solved it now. for the guns I simply use lookAt(player). Unfortunately they now look immediately at the player. If someone has an idea how to make them slowly turn towards the player as well without using quanternions (they don’t seem to work with children) that would be greatly appreciated.
I now have what I think is a pretty good solution:
I use the above mentioned method to rotate the turret base. The guns are no longer a child of the turret. I then use the same transformation for the guns, but in the end I say:
guns.eulerAngles.y = transform.eulerAngles.y; // where transform is the turret
That seems to work, where with parenting relations, even when I don’t transform the guns at all, their rotation is not in sync with the parent. Which I don’t get, I thought parenting was independent of the type of transform of the parent object.
I know this won’t work if the turret is rotated around any but the y axis, but luckily, they all point up.
I was thinking that you should first calculate vector v like:
Vector3 v = transform.position - player.position;
v.y = 0;
v.Normalize();
newRotation = Quaternion.LookRotation(v);
For smooth rotation you could do lerp or if you are using quaternions then slerp, like in this eg.:
rotation = Quaternion.Slerp(rotation, newRotation, damping*Time.deltaTime);
Where damping is some float value. The bigger you make it the faster will go toward the newRotation.