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.

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