CarEngine | Showreel

PHOTO EMBED

Tue May 17 2022 16:08:48 GMT+0000 (Coordinated Universal Time)

Saved by @BiscuitTinx #c#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CarEngine : MonoBehaviour
{
    public Transform path;
    public float maxSteerAngle = 45f;
    public WheelCollider WheelFL, WheelFR, WheelBR, WheelBL;
    public GameObject ObjectWheelFL, ObjectWheelFR, ObjectWheelBR, ObjectWheelBL;
    public float speed = 25f;

    private List<Transform> nodes; 
    private int currentNode = 0;
    
    // Start is called before the first frame update
    private void Start()
    {
        Transform[] pathTransforms = path.GetComponentsInChildren<Transform>();
        nodes = new List<Transform>();

        for (int i = 0; i < pathTransforms.Length; i++)
        {
            if (pathTransforms[i] != path.transform)
            {
                nodes.Add(pathTransforms[i]);
            }
        }
    }

    // Update is called once per frame
    private void FixedUpdate()
    {
        ApplySteer();
        Drive();
        CheckWaypointDistance();
    }

    private void ApplySteer()
    {
        Vector3 relativeVector = transform.InverseTransformPoint(nodes[currentNode].position);
        float newSteer = (relativeVector.x / relativeVector.magnitude) * maxSteerAngle;
        WheelFL.steerAngle = newSteer;
        WheelFR.steerAngle = newSteer;
    }

    private void Drive()
    {
        WheelFL.motorTorque = speed;
        WheelFR.motorTorque = speed;
    }
    
    private void CheckWaypointDistance()
    {
        if (Vector3.Distance(transform.position, nodes[currentNode].position) < 0.5f)
        {
            if(currentNode == nodes.Count - 1)
            {
                currentNode = 0;
            }
            else
            {
                currentNode++;
            }
        }
    }

}

//https://www.youtube.com/watch?v=oMkq1ntLZPc
//https://www.youtube.com/watch?v=AXOUgbPiugE
//https://www.youtube.com/watch?v=neer0N4AiIQ
content_copyCOPY