Hey guys,
This is my forst post so please bear with me I’m still learning C# and Unity.
I am creating a super simple game just to get used to Unity.It’s a 2D shooter where you have a “gun” in the center of the screen. Players are able to rotate the gun on it’s z axis to be able to shoot left and right. See attached screenshot for a visual (haven’t added movement to my bullets yet).
I wanted to restrict the rotation of the gun in a 0-180 degree angle (when looking at the game). So far it all works as intended, but doubt it’s the optimal way of doing it. I also don’t fully understand my code as I’ve found some answers here that have helped me get to where I am.
Here is the code:
// Update is called once per frame
void Update ()
{
float amtToMove = (Input.GetAxisRaw("Horizontal") * moveSpeed * Time.deltaTime);
myBase.Rotate (0, 0, amtToMove * -1);
if(myBase.rotation.z > 0.7f)
myBase.rotation = Quaternion.Euler(0, 0, 90);
if(myBase.rotation.z < -0.7f)
myBase.rotation = Quaternion.Euler(0, 0, -90);
}
My questions:
-
Is this a good way of rotating the Z axis? I found when I used GetAxisRaw"Horizontal" I had to multiply it with -1 to get the desired result (moving angle left and right).
-
Is there a better way of finding the absolute horizontal left and right values for myBase.rotation? I simply read it of the object in the inspector and found it to be 0.7 and -0.7.
-
When using Quaternion.Euler my first guess was to use 0 and 180 for maximum values for left and right rotation. Turns out it’s 90 and -90. Is this the correct way of setting a max angle?
Apologies if these are stupid questions. Still trying to learn. Thanks in advance!
Nick