I'm trying to create a mobile joystick using this free package from Unity. Here is the code for rotation which seems to be working fine. I just want to clamp the rotation to +90 or -90 degress. I have tried using the mathf.clamp function but the plane(player) completes a full rotation.

public Joystick joystick;
float rotateVertical;
float rotateHorizontal;

float minClamp = -90.0f;
float maxClamp = 90f;

void Update()
    rotateVertical = Mathf.Clamp(joystick.Vertical * 1f, minClamp, maxClamp);

    rotateHorizontal = Mathf.Clamp(joystick.Horizontal * -1f, minClamp, maxClamp);

    transform.Rotate(rotateVertical, 0, rotateHorizontal);

If I change the value of minClamp to 0, then the plane doesn't rotate on the negative x axis but is still able to complete a full rotation on the positive x axis. Can someone please help me?


1 Answer 1


It looks like what you're trying to clamp isn't the joystick input, it's the rotation of the object.

For that, you want to apply something a bit like this:

public float minClamp = -90.0f;
public float maxClamp = 90f;
public float sensitivity = 1f;

Quaternion _initialRoation;
float _pitch, yaw;

void Start() {
    _initialRotation = transform.rotation;

void Update() {
    _pitch = Mathf.Clamp(_pitch + joystick.Vertical * sensitivity, minClamp, maxClamp);

    _yaw = Mathf.Clamp(_yaw - joystick.Horizontal * sensitivity, minClamp, maxClamp);

    transform.rotation = _initialRotation * Quaternion.Euler(pitch, yaw, 0);
  • \$\begingroup\$ ..thanks for the help..this is working fine now......can this also work for movement in the x and y axis? Do I just have to change transform.rotation to transform.translate? \$\endgroup\$ Commented Jun 15, 2020 at 17:23
  • \$\begingroup\$ Don't confuse a noun and a verb. Transform.Rotate and Transform.Translate are verbs, they say "move by this much". Clamping the increment doesn't limit your range of motion. Transform.rotation and Transform.position are your nouns. They're the current position or orientation of the object, so you can clamp them fruitfully. \$\endgroup\$
    – DMGregory
    Commented Jun 15, 2020 at 17:33
  • \$\begingroup\$ oh....thanks for the clarification... \$\endgroup\$ Commented Jun 17, 2020 at 16:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .