Mathf.Clamp on Z-Axis to limit rotation using transform.Rotate

Hi,

I’m using a leap to rotate an object on its z-axis. Currently I am unsure about how to properly use Mathf.Clamp to limit the rotation using transform.Rotate. Tho I realize this is currently incorrect, this is my starting point. In this case roll is the raw position of the palm in space. Suggestions? Thanks.

if ((roll > 0.1f) && (roll < 0.6f)) {
      transform.Rotate(Mathf.Clamp(0,0,rotSpeed * Time.deltaTime ),0f,10.0f); 
}else if ((roll < 0) && (roll > -0.8)){
       transform.Rotate(Mathf.Clamp(0,0,-rotSpeed * Time.deltaTime ),0f,-10.0f); 
}

That approach won’t work. The math in clamp is wrong (it’s always 0,) but beyond that, the whole idea is wrong.

Think of adding 1 to a number, but not past 30. x=x+1 is “dumb”. It will add 1 to any number the same as Rotate will spin any angle. if(x<30) x=x+1; solves it. It’s our job, using the if, to only run the “add 1” when we need to. Another way is x=x+1; x=Math.Clamp(x,0,30);. In that case, it’s our job to personally examine the final value and fix it.

Then think about x=x+Math.Clamp(y,0,30);. Suppose x is 20 and y is 40. This checks y, clamps to 30, then adds 30 to x giving 50. Uck. If you did it again, x would be 80. In no way does it check the final value of x. You can’t write one command that means “add 1 but not past 30.” The same say, you can’t write one command that means “spin, but not past 30 degrees.”

Using Rotate to only go so far is tricky. The Answers for it here look complicated, because it is. You can sort of check transform.euler.z, either before or after the rotate. That bugs out in many cases, but lots of people use it. Or, depending exactly on the limits and ways you can spin, you can check transform.up.y or Quaternion.Angle … .

But, like adding 1, the way to do it is to check the angle before or after. And either don’t do the spin, or “fix” the spin afterwards.