Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- [RequireComponent(typeof(Rigidbody))]
- public class CarController : MonoBehaviour
- {
- public float torque = 5000;
- public float brakingTorque = 10000;
- public float maxSteer = 45;
- public List<WheelCollider> backWheels;
- public List<WheelCollider> frontWheels;
- public List<Transform> wheelMeshes;
- public List<Transform> springMeshes;
- public float downForce = 1;
- public float ForwardVelocity { private set; get; }
- List<WheelCollider> wheels;
- Rigidbody rb;
- float throttle = 0.0f;
- float braking = 0.0f;
- float steering = 0.0f;
- float minSteering = 0.1f;
- // Start is called before the first frame update
- void Start()
- {
- wheels = new List<WheelCollider>();
- foreach (WheelCollider wheel in backWheels)
- wheels.Add(wheel);
- foreach (WheelCollider wheel in frontWheels)
- wheels.Add(wheel);
- rb = GetComponent<Rigidbody>();
- }
- // Update is called once per frame
- void FixedUpdate()
- {
- throttle = Input.GetAxis("Vertical");
- braking = Input.GetAxis("Jump");
- steering = Mathf.Lerp(steering, Input.GetAxis("Horizontal") * Mathf.Max(minSteering, 1.0f / (0.04f * ForwardVelocity + 1.0f)), Time.deltaTime * 10);
- foreach (WheelCollider wheel in backWheels)
- {
- wheel.motorTorque = throttle * torque;
- }
- ForwardVelocity = rb.velocity.magnitude * 3.6f;
- for (int i = 0; i < 2; ++i)
- {
- WheelCollider wheel = frontWheels[i];
- wheel.steerAngle = steering * maxSteer;
- springMeshes[i + 2].localRotation = Quaternion.AngleAxis(steering * maxSteer, Vector3.up);
- }
- Ray downRay;
- RaycastHit hit;
- for (int i = 0; i < 4; ++i)
- {
- WheelCollider wheel = wheels[i];
- wheelMeshes[i].Rotate(wheel.rpm / 60.0f * Time.deltaTime * 360.0f, 0, 0);
- float distance = 0.2f;
- if (wheel.isGrounded)
- {
- downRay = new Ray(wheels[i].transform.position, -transform.up);
- if (Physics.Raycast(downRay, out hit, 1.0f, ~(1<<9)))
- {
- Debug.Log(hit.collider.gameObject.name);
- distance = hit.distance - 0.42f;
- }
- }
- distance = Mathf.Clamp(distance, 0.0f, 0.2f);
- springMeshes[i].localPosition = new Vector3(springMeshes[i].localPosition.x, -distance, springMeshes[i].localPosition.z);
- }
- foreach (WheelCollider wheel in wheels)
- wheel.brakeTorque = braking * brakingTorque;
- rb.AddForce(-transform.up * downForce * ForwardVelocity);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement