Search code examples
c#unity-game-enginemonodevelop

Wheel steering in Unity 3D using C#


I'm quite new when it comes to scripting in C# and I've been stuck with this problem for few days now. I have made this script so that my car can move through map, and the wheels are rotating on Z axis. Script:

using UnityEngine;
using System.Collections;

public class CarMovement : MonoBehaviour
{
    public Transform wheelFLTrans;
    public Transform wheelFRTrans;
    public Transform wheelBRTrans;
    public Transform wheelBLTrans;
    public float MotorForce;
    public float Steerforce;
    public WheelCollider GumaPD;
    public WheelCollider GumaPLj;
    public WheelCollider GumaZD;
    public WheelCollider GumaZLJ;


    void Start()
    {
    }
    // Update is called once per frame


    void Update()
    {
        float v = Input.GetAxis("Vertical") * MotorForce;
        float h = Input.GetAxis("Horizontal") * Steerforce;
        GumaPD.motorTorque = v;
        GumaPLj.motorTorque = v;
        GumaPD.steerAngle = h;
        GumaPLj.steerAngle = h;
        wheelFLTrans.Rotate(Vector3.forward * GumaPLj.rpm * 2 * Mathf.PI / 60.0f * Time.deltaTime * Mathf.Rad2Deg);
        wheelFRTrans.Rotate(Vector3.forward * GumaPD.rpm * 2 * Mathf.PI / 60.0f * Time.deltaTime * Mathf.Rad2Deg);
        wheelBRTrans.Rotate(Vector3.forward * GumaZD.rpm * 2 * Mathf.PI / 60.0f * Time.deltaTime * Mathf.Rad2Deg);
        wheelBLTrans.Rotate(Vector3.forward * GumaZLJ.rpm * 2 * Mathf.PI / 60.0f * Time.deltaTime * Mathf.Rad2Deg);
        wheelFRTrans.eulerAngles = new Vector3(0f, Input.GetAxis("Horizontal"), 0f);
    }

}

Now my problem is:

I would like to add wheel steering while I'm driving my car through the map. Like when I press A or D key , the wheels would steer to the way depending on what key I'm pressing (A or D). I've tried with this line of code:

       **wheelFRTrans.localEulerAngles = new Vector3(0, wheelFR.steerAngle, 0);**

This works, but then for some reason my front wheels stop rotating :(. Can someone help me out with this please, I've been stuck with this for days now :(. I want that my wheels can rotate and steer at the same time :/.

I'm sorry for my bad English.

Thanks!


Solution

  • i solved the problem:

        Tires[0].transform.Rotate(Vector3.right,-BLWheel.rpm * 2 * Mathf.PI / 60.0f * Time.deltaTime * Mathf.Rad2Deg,Space.Self);
        Tires[1].transform.Rotate(Vector3.right,BRWheel.rpm * 2 * Mathf.PI / 60.0f * Time.deltaTime * Mathf.Rad2Deg,Space.Self);
    
        Tires[2].transform.Rotate(Vector3.right, FLWheel.rpm * 2 * Mathf.PI / 60.0f * Time.deltaTime * Mathf.Rad2Deg,Space.Self);
        Tires[3].transform.Rotate(Vector3.right, -FRWheel.rpm * 2 * Mathf.PI / 60.0f * Time.deltaTime * Mathf.Rad2Deg,Space.Self);
    
        Tires[2].transform.Rotate(Vector3.up, FLWheel.steerAngle - tempAngle,Space.World);
        Tires[3].transform.Rotate(Vector3.up, FLWheel.steerAngle - tempAngle,Space.World);
        tempAngle = FLWheel.steerAngle;