I have a vehicle that moves left or right on the X-axis using wheel colliders. It is walled in by two rigid bodies on either side of the X-axis but I want the the vehicle to stop just before hitting the walls, as hitting them will cause the vehicle to move off track. This basic script works:
public static float xBoundry = 18.2f;
if(transform.position.x < -xBoundry + 1.5f)
transform.position = new Vector3(-xBoundry + 1.5f, 0, 0);
else if
(transform.position.x > xBoundry - 1.5f)
transform.position = new Vector3(xBoundry - 1.5f, 0, 0);
But it causes the vehicle to jitter as its collider continually exceeds the boundary and gets pushed back. I read that using Mathf.Clamp can set a boundary without the jitter so I tried it in my script:
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;
transform.position.x = Mathf.Clamp (transform.position.x + gas, -18.2f, 18.2f);
But I get the error
Cannot modify a value type return value of `UnityEngine.Transform.position’. Consider storing the value in a temporary variable
I’m a little confused on how I put all this information together.