0
\$\begingroup\$

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?

\$\endgroup\$
1
\$\begingroup\$

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);
}
| improve this answer | |
\$\endgroup\$
  • \$\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\$ – single arrow games Jun 15 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 Jun 15 at 17:33
  • \$\begingroup\$ oh....thanks for the clarification... \$\endgroup\$ – single arrow games Jun 17 at 16:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.