# Clamp joystick rotation in Unity

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?

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);
}

• ..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? Jun 15 '20 at 17:23
• 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. Jun 15 '20 at 17:33
• oh....thanks for the clarification... Jun 17 '20 at 16:35