- Home /
Having trouble rotating a turret
I need to rotate a turret around the Z axis. The turret is successfully rotating around the z axis however, the turrets x rotation becomes 0 when it should stay at -90, and i cannot figure out how to rotate the turret and keep the x rotation at -90. Here is the code i have to rotate the turret.`public class PT_Turret_rotate : MonoBehaviour {
public GameObject player;
private Vector3 lookDir;
private void Update()
{
lookDir = player.transform.position - transform.position;
lookDir.y = 0;
transform.rotation = Quaternion.LookRotation(lookDir);
}
Answer by MacDx · Sep 25, 2017 at 06:06 PM
I think the problem is the vector you are passing to the LookRotation method. You said that you:
need to rotate a turret around the Z axis
This means that you will only move in Z degrees and X and Y degrees should always be 0. However, you are passing a vector that will result in a rotation around the Y axis (depending on how the player can move). So what you need to is leave the X and Y values as they are and set the Z value to zero instead.
In unity, up is the y axis. So if you are using standard unity orientation, you want to only change the y rotation value
I tried your answer and the effect was unfortunately not helpful I made an illustration in hopes of you seeing the problem. The turret always ends on its side and rotates with the base and not the top. even if i leave the Z axis at zero the turret still ends up sideways and facing the opposite direction of the player. Even when rotating it on the X axis it still is sideways. could it be an error with the model?
Ahh I see, so (assu$$anonymous$$g your camera is pointing downwards in your scene, hence the top view) you don't really want to rotate around Z axis, what you really want is rotation around the Y axis. In that case, yeah, my answer won't help. Give me a few $$anonymous$$utes to answer with this new info in $$anonymous$$d.
Ok Drksteel, I set up a project with a camera facing down ( x rotation to 90 degrees) I placed a player that can move in x and z direction and I placed a turret with exactly the same script you are showing here and it works perfectly. Either you have a different setup from what I am assu$$anonymous$$g or your player movement is causing the problem.
I'll zip and post a link to the project so you can check it out:
Edit: Here it is https://drive.google.com/open?id=0Bx9pF2CVhb6pVjdYTWNjcThWN00
I have figured out that the error is the model and not the scripting, the code is working perfectly fine its just the turret's base rotation is actually just sideways. Thank you for helping me figure that out.
Your answer
Follow this Question
Related Questions
Why is this rotation not performed as expected? 1 Answer
The object turn but the axis dont (SOLVED) 3 Answers
Smooth Camera Rotation After 2 Seconds 1 Answer
Question on Forcing a Specific Rotation 1 Answer
Vector3.RotateTowards Problem 1 Answer