Hello everyone,
I want to make sure I am doing this correctly. It appears to work, but I know that doesn’t always mean it is the proper way to achieve something.
I have a 2D game. In this game I have a gun turret that I only want the player input to rotate the Z Axis. Using the scene tools I determined the maximum and minimum Z to be 25 and -25.
Here is my implementation, please let me know what I should do differently.
public float turretSpeed = 50.0f;
public float maxAngleDown = -25.0f;
public float maxAngleUp = 25.0f;
private float zAxis = 0.0f;
// This function is called every fixed framerate frame, if the MonoBehaviour is enabled
private void FixedUpdate()
{
float zInput = Input.GetAxisRaw("VerticalGun");
if (zInput != 0)
{
zAxis += (Time.deltaTime * zInput * turretSpeed);
zAxis = Mathf.Clamp(zAxis, maxAngleDown, maxAngleUp);
transform.rotation = Quaternion.Euler(0, 0, zAxis);
}
}
The code seems to be correct , other than the high turretSpeed. At 50 it will rotate from one end to the other in 1 second. and from straight up to far left or far right in 1/2 a second. This is how I would do it, does it do anyting odd or weird or does it work correctly?
Just note if you ever try to get the angle its currently at and manipulate it, it won’t be a negative value if you pointing to the left. from 0 to -25 will return 0->335. Unity transforms all your negatives it to the positive rotation in 0->360. However since your keeping track of it outside and then just inputting the values , unity will convert it afterwards and everything should work smoothly.
Thank you takatok.
I definitely agree, the turret speed is too fast, but that was mainly for me to know it was moving; I tried a few different ways until I read more of the Unity docs.
To answer your question, yes it is behaving as I desired. Except the speed but that will be easy enough to fix.
Your choice of using a float to in turn drive a rotation is what I consider Goor Practice™.
There are too many tutorials out there that suggest applying successive rotations, which always accumulate more and more error.
By driving it with a float you avoid all of those problems. Your approach keeps the data flow simple and one-directional by NOT reading back the .eulerAngles of something you are already driving with a float. I approve. 
1 Like
Thank you very much Kurt-Dekker!