- Home /
How to limit the rotation of a RigidBody ?
Hi there,
I have some problems with limitting the X-axis and the Z-axis.
I have a tray with a maze on it, on my scene, and i would like to limit the rotation of the tray.

Basically, i receive X and Z values from an external device, a RaspBerry actually, communicating with a TCP Server, and updating the rotation of the tray every seconds. My problem here is just the rotation part, wich i want to limit from -30 to 30 for example.
Here's the script attached to the tray:
public class ControlTray : MonoBehaviour
{
public float speedRot;
private float x;
private float z;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody> ();
ServerTCP.Level = 0;
}
void FixedUpdate()
{
x = ServerTCP.x * speedRot * Time.deltaTime;
z = ServerTCP.z * speedRot * Time.deltaTime;
Vector3 Moves= new Vector3(x,0.0f,z);
rb.transform.Rotate (Moves);
}
}
I saw other topic trating the same subject, but none of them actually helped me.
I mean, i saw that Mathf.Clamp seems to be the option i need, but i really didn't understand how to use it.
I'm really looking forwards your answers,
Thanks in advance.
Bryan.
Answer by Dave-Carlile · Mar 22, 2017 at 06:19 PM
The Mathf.Clamp documentation is fairly clear and provides examples. Basically the idea is that you pass the value you want to clamp along with the minimum and maximum value. The function returns either the value you passed in if it was within the min and max, or returns the minimum value if the passed value is less than min, or returns the maximum value if the passed value is greater than max.
Here's some pseudocode to show how the function works
float value = 10.0f;
float minValue = -30.0f;
float maxValue = 30.0f;
if (value < minValue)
return minValue;
else if (value > maxValue)
return maxValue;
else
return value;
Using part of your example code to illustrate:
x = Mathf.Clamp(ServerTCP.x * speedRot * Time.deltaTime, -30.0f, 30.0f);
Thank you @Dave-Carlile for your answer.
Your example is pretty good and makes me understand the idea of how it's working.
However, after trying this method with my code, i didn't get any error, but still, my tray continue to rotate after he passed the max, or $$anonymous$$ value, it didn't stop.
Transform.Rotate adds the rotation you pass in to the object's current rotation. If you want to set a specific rotation you use the Transform.rotation property.
Based on your sample code (and the sample I provided) you're clamping the inco$$anonymous$$g rotation value, then adding that to the object's current rotation. Ins$$anonymous$$d you'll need to clamp the final rotation.
Your answer