Simple 2D Gun Rotation on Z-axis

Hey guys,

This is my forst post so please bear with me :slight_smile: 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:

  1. 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).

  2. 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.

  3. 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

1030485--38216--$Screen Shot 2012-09-08 at 09.52.17.png

  1. Yep, pretty standard way to rotate things, nice and simple.

  2. rotation is a Quaternion, which means its x, y, z, and w components don’t mean anything unless you know All Of The Maths There Are. Use the Quaternion class functions to get values you can make sense of . You actually want to use rotation.eulerAngles.z - that’ll get you degrees instead of Quaternion Who Knows Whatnesses.

  3. Also yep. Zero degrees of rotation points along one of the world axes - +X, +Y, +Z. So, if you want 180* centered on a world axis, -90 to +90 is the right limits.