- Home /
How to make a steering wheel that rotates when wheels do?
I have been searching for an answer for the past two days on here and Stackoverflow and I just cant find a solution. For the past week I've been trying to make a driving game. I have a simple working CarController. Right now the steering wheel just rotates to the left and right when wheels do, but they are not synchronized and they don't stop and return to certain angles. I want, so that the wheel turns at the same angle as the wheel and that it stops when the wheel is turned to certain angles and returns to a 0 angle when the wheel is not turned. I'm a beginner at coding, so if someone can find a solution to this problem, please share.
Here's my CarController script:
public class CarController : MonoBehaviour
{
private float horizontalInput;
private float verticalInput;
private float steeringAngle;
public WheelCollider frontLeftC, frontRightC;
public WheelCollider rearLeftC, rearRightC;
public Transform frontLeftT, frontRightT;
public Transform rearLeftT, rearRightT;
public float maxSteerAngle=30;
public float SteerSpeed = 100;
public float power=50;
public GameObject wheel;
float rotations = 0;
public void GetInput()
{
horizontalInput = Input.GetAxis("Horizontal");
verticalInput = Input.GetAxis("Vertical");
}
private void Steer()
{
steeringAngle = maxSteerAngle * horizontalInput;
frontLeftC.steerAngle = steeringAngle;
frontRightC.steerAngle = steeringAngle;
}
private void Accelerate()
{
frontLeftC.motorTorque = verticalInput * power;
frontRightC.motorTorque = verticalInput * power;
rearLeftC.motorTorque = verticalInput * power;
rearRightC.motorTorque = verticalInput * power;
}
private void UpdateWheelPoses()
{
UpdateWheelPose(frontLeftC, frontLeftT);
UpdateWheelPose(frontRightC, frontRightT);
UpdateWheelPose(rearLeftC, rearLeftT);
UpdateWheelPose(rearRightC, rearRightT);
}
private void UpdateWheelPose(WheelCollider collider, Transform transform)
{
Vector3 pos = transform.position;
Quaternion quat = transform.rotation;
collider.GetWorldPose(out pos, out quat);
transform.position = pos;
transform.rotation = quat;
}
private void FixedUpdate()
{
GetInput();
Steer();
Accelerate();
UpdateWheelPoses();
if (horizontalInput>0)
{
wheel.transform.Rotate(Vector3.forward * Time.deltaTime * SteerSpeed);
rotations += steeringAngle;
}
if (horizontalInput < 0)
{
wheel.transform.Rotate(-Vector3.forward * Time.deltaTime * SteerSpeed);
rotations -= steeringAngle;
}
}
}
Your answer
Follow this Question
Related Questions
Car Front Tires rotation clamped between 270° - 90° 0 Answers
CAR ROTATING HELP 2 Answers
Car Steering Relative to Car Speed 2 Answers
Translating in world space only on y axis? 0 Answers
Car Question 2 Answers