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
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter