- Home /
Clamping movement range on X-axis
I have a vehicle that moves left or right on the X-axis using wheel colliders but I need to restrict it to a certain range. I'm using Mathf.clamp because apparently it doesn't cause the rigidbody to jitter like other methods do. Here is my script which gives a couple of errors:
void FixedUpdate(){
gas = Input.GetAxis("Horizontal");
frontLeftWheel.motorTorque = enginePower * gas;
frontRightWheel.motorTorque = enginePower * gas;
rearLeftWheel.motorTorque = enginePower * gas;
rearRightWheel.motorTorque = enginePower * gas;
frontRightMiddle.motorTorque = enginePower * gas;
frontRightBackMiddle.motorTorque = enginePower * gas;
frontLeftMiddle.motorTorque = enginePower * gas;
backLeftMiddle.motorTorque = enginePower * gas;
Vector3 temp = new Vector3(-xBoundry, 0, 0);
temp.x = Mathf.Clamp(temp.x, -18.2, 18.2);
transform.position = temp;
I understand basically how Mathf.Clamp works. You state the value and then its range between two floats, then you store the changing transform in a temporary variable and reassign it (which I think I'm going wrong). But I'm confused what the value here would be. Is it the transform position or is it the Input?
I'm guessing you want:
Vector3 temp = transform.position;
temp.x = $$anonymous$$athf.Clamp(temp.x, -18.2f, 18.2f);
transform.position = temp;
I'm getting two errors for the second line of the clamp script:
"The best overloaded method match for `UnityEngine.$$anonymous$$athf.Clamp(float, float, float)' has some invalid arguments"
and
"Argument '#2' cannot convert 'double' expression to type 'float'"
By default in C#, floating point numbers are doubles. Unity uses floats (a lower precision version of floating point numbers). In order to declare floats, you need to add a 'f' suffix. I edited my comment to fix the problem.
Damn, that's my fault I should've noticed that. Thanks! Got it working