Limit a rotation (transform.Rotate with Input.GetAxis) ? [C#]

Hello everyone :slight_smile:

Basically, everything is in the question, but here’s further details:

Primary question : I have a cannon that rotates horizontally and vertically when I use the GetAxis (horizontal or vertical) with keys.

How to limit a rotation using transform.Rotate and Input.GetAxis. I need different angle limits for both axis (Horizontal : can turn between -80° and 80° ; Vertical : can turn between -45° and 80°).

It is a question that has been asked a lot as I can see, but the forever beginner I am cannot make it work…


Secondary question : At first, I was working with Input.GetKey, now I work with Input.GetAxis because I’ve read it was better. Is it really ?. What’s the best way to code a key input?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CanonBehaviour : MonoBehaviour {

	public GameObject HorizontalRot;
	public GameObject VerticalRot;
	float rotSpeed = 7f;

	void Update () {
		
		if (Input.GetMouseButton (1)) {
			rotSpeed = 35f;
		} else {
			rotSpeed = 7f;
		}

		HorizontalRot.transform.Rotate (0.0f, (Input.GetAxis ("Horizontal")) * rotSpeed * Time.deltaTime, 0.0f);
		VerticalRot.transform.Rotate (0.0f, 0.0f, (Input.GetAxis ("Vertical")) * rotSpeed * Time.deltaTime);

	}
}

If you think that what I have now is not the best way to go about it, let me know. I’m here to learn.

Thanks for any kind of help, that’s very much appreciated :slight_smile:


EDIT : Just to be clear, I don’t expect a full script or anything, just a hint or a quick explanation of how that can be achieve is enough.

Have a nice day :slight_smile:

For your primary question try this :

private float speed;

        private float y;

        private float z;

        private void Start()
        {
            y = transform.localEulerAngles.y;
            z = transform.localEulerAngles.z;
        }

        private void Update()
        {
            speed = Input.GetMouseButton(1) ? 5f : 2f;

            var horizontal = Input.GetAxis("Horizontal");
            y += horizontal * speed;
            y = Mathf.Clamp(y, -80, 80);
            
            if (y < 80 && y > -80)
            {
                transform.localEulerAngles = new Vector3(0, y, z);
            }

            var vertical = Input.GetAxis("Vertical");
            z += vertical * speed;
            z = Mathf.Clamp(z, -45.0f, 80.0f);
            if (z < 80.0f && z > -45.0f)
            {
                transform.localEulerAngles = new Vector3(0, y, z);
            }
        }

For second question : GetKey is a bool and GetAxis is a float between -1 and 1 it starts from zero and increase/decrease while button is pressed down. I’m not sure which one is better, if you want controller/joystick support GetAxis is great, if you want immediate respond GetKey or GetButton is better.