CarController.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class CarController : MonoBehaviour
  5. {
  6. public Wheel[] turningWheels;
  7. public Wheel[] drivingWheels;
  8. public List<Wheel> allWheels;
  9. public Rigidbody rb;
  10. public float TopSpeed = 10;
  11. public float Deceleration;
  12. public float BrakePower = 3;
  13. public AnimationCurve PowerCurve;
  14. public float EnginePower = 5;
  15. public float curSpeed;
  16. [Header("Steering")]
  17. public float maxSteerAngle = 25;
  18. public float minSteerAngle = 10;
  19. void Awake(){
  20. foreach(Wheel wheel in turningWheels){
  21. wheel.myCar= this;
  22. if(!allWheels.Contains(wheel)){allWheels.Add(wheel);}
  23. }
  24. foreach(Wheel wheel in drivingWheels){
  25. wheel.myCar= this;
  26. if(!allWheels.Contains(wheel)){allWheels.Add(wheel);}
  27. }
  28. }
  29. void FixedUpdate()
  30. {
  31. if(Input.GetKeyDown(KeyCode.R)){transform.eulerAngles = new Vector3(0,0,0);}
  32. curSpeed = Vector3.Dot(transform.forward, rb.velocity);
  33. float verticalInput = Input.GetAxis("Vertical");
  34. if((verticalInput >0 && curSpeed < 0) || (verticalInput <0 && curSpeed > 0)){
  35. foreach(Wheel wheel in allWheels){
  36. wheel.Brake();
  37. }
  38. }
  39. foreach(Wheel wheel in drivingWheels){
  40. wheel.Rotate(verticalInput);
  41. }
  42. foreach(Wheel wheel in turningWheels){
  43. wheel.Steer(Input.GetAxis("Horizontal"));
  44. }
  45. }
  46. }