Advertisement
Purianite

Untitled

Feb 17th, 2017
349
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 9.48 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class CarController : MonoBehaviour {
  5.  
  6. public float deviceAccelerometerSensitivity = 2f; //how sensitive our mobile accelerometer will be
  7. public float deadZone = .001f; //controls mobile device tilting dead zone
  8. public float horizontal; //horizontal input control, either mobile control or keyboard
  9. public float maxSpeedToTurn = 0.25f; //keeps car from turning until it's reached this value
  10.  
  11. // the physical transforms for the car's wheels
  12. public Transform frontLeftWheel;
  13. public Transform frontRightWheel;
  14. public Transform rearLeftWheel;
  15. public Transform rearRightWheel;
  16.  
  17. //these transform parents will allow wheels to turn for steering/separates steering turn from acceleration turning
  18. public Transform LFWheelTransform;
  19. public Transform RFWheelTransform;
  20.  
  21. //do not adjust this, but you will be able to read it in the inspector, and read it's value for a speedometer
  22. public float mySpeed;
  23.  
  24. // car physics adjustments
  25. public float power = 1200f;  
  26. public float maxSpeed = 50f;
  27. public float carGrip = 70f;
  28. public float turnSpeed = 2.5f; //keep this value somewhere between 2.5 and 6.0
  29.  
  30. //bunch of variables we do not adjust, script handles these internally
  31. private float slideSpeed;
  32. private Vector3 carRight;
  33. private Vector3 carFwd;
  34. private Vector3 tempVEC;
  35. private Vector3 rotationAmount;
  36. private Vector3 accel;
  37. private float throttle;
  38. private Vector3 myRight;
  39. private Vector3 velo;
  40. private Vector3 flatVelo;
  41. private Vector3 relativeVelocity;
  42. private Vector3 dir;
  43. private Vector3 flatDir;
  44. private Vector3 carUp;
  45. private Transform carTransform;
  46. private Rigidbody thisRigidbody;
  47. private Vector3 engineForce;
  48. private float actualGrip;
  49. private Vector3 turnVec;
  50. private Vector3 imp;
  51. private float rev;
  52. private float actualTurn;
  53. private float carMass;
  54. private Transform[] wheelTransform = new Transform[4]; //these are the transforms for our 4 wheels
  55. private AudioSource myAudioSource;
  56.  
  57.     void Start()
  58.     {
  59.         InitializeCar();
  60.     }
  61.  
  62.     void InitializeCar()  
  63.     {
  64.         // Cache a reference to our car's transform
  65.         carTransform = GetComponent<Transform>();
  66.         // cache the rigidbody for our car
  67.         thisRigidbody = GetComponent<Rigidbody>();  
  68.         // cache a reference to the AudioSource
  69.         myAudioSource = GetComponent<AudioSource>();
  70.         // cache our vector up direction
  71.         carUp = carTransform.up;
  72.         // cache the mass of our vehicle
  73.         carMass = thisRigidbody.mass;
  74.         // cache the Forward World Vector for our car
  75.         carFwd = Vector3.forward;
  76.         // cache the World Right Vector for our car
  77.         carRight = Vector3.right;
  78.         // call to set up our wheels array
  79.         SetUpWheels();
  80.         // we set a COG here and lower the center of mass to a
  81.         //negative value in Y axis to prevent car from flipping over
  82.         thisRigidbody.centerOfMass = new Vector3(0f, -0.75f, .35f);  
  83.     }
  84.  
  85.     void Update()
  86.     {
  87.         // call the function to start processing all vehicle physics
  88.         CarPhysicsUpdate();
  89.  
  90.         //call the function to see what input we are using and apply it
  91.         CheckInput();
  92.     }
  93.  
  94.     void LateUpdate()
  95.     {
  96.         // this function makes the visual 3d wheels rotate and turn
  97.         RotateVisualWheels();
  98.  
  99.         //this is where we send to a function to do engine sounds
  100.         EngineSound();
  101.     }
  102.  
  103.     void SetUpWheels()
  104.     {
  105.         if ((null == frontLeftWheel || null == frontRightWheel || null == rearLeftWheel || null == rearRightWheel))
  106.         {
  107.             Debug.LogError("One or more of the wheel transforms have not been assigned on the car");
  108.             Debug.Break();
  109.         }
  110.         else
  111.         {
  112.             //set up the car's wheel transforms
  113.             wheelTransform[0] = frontLeftWheel;
  114.             wheelTransform[1] = rearLeftWheel;
  115.             wheelTransform[2] = frontRightWheel;
  116.             wheelTransform[3] = rearRightWheel;
  117.         }
  118.     }
  119.  
  120.     void RotateVisualWheels()
  121.     {
  122.         Vector3 tmpEulerAngles = LFWheelTransform.localEulerAngles;  
  123.         tmpEulerAngles.y = horizontal * 30f;
  124.  
  125.         // front wheels visual rotation while steering the car
  126.         LFWheelTransform.localEulerAngles = tmpEulerAngles;
  127.         RFWheelTransform.localEulerAngles = tmpEulerAngles;
  128.  
  129.         rotationAmount = carRight * (relativeVelocity.z * 1.6f * Time.deltaTime * Mathf.Rad2Deg);
  130.  
  131.         wheelTransform[0].Rotate(rotationAmount);
  132.         wheelTransform[1].Rotate(rotationAmount);
  133.         wheelTransform[2].Rotate(rotationAmount);
  134.         wheelTransform[3].Rotate(rotationAmount);
  135.     }
  136.  
  137.     void CheckInput()
  138.     {
  139.         //Mobile platform turning input...testing to see if we are on a mobile device.              
  140.         if (Application.platform == RuntimePlatform.IPhonePlayer || (Application.platform == RuntimePlatform.Android))
  141.         {
  142.             // we give the acceleration a little boost to make turning more sensitive
  143.             accel = Input.acceleration * deviceAccelerometerSensitivity;
  144.  
  145.             if (accel.x > deadZone || accel.x < -deadZone)
  146.             {
  147.                 horizontal = accel.x;
  148.             }
  149.             else
  150.             {
  151.                 horizontal = 0;
  152.             }
  153.             throttle = 0;
  154.  
  155.             foreach (Touch touch in Input.touches)
  156.             {
  157.                 if (touch.position.x > Screen.width - Screen.width / 3 && touch.position.y < Screen.height / 3)
  158.                 {
  159.                     throttle = 1f;
  160.                 }
  161.                 else if (touch.position.x < Screen.width / 3 && touch.position.y < Screen.height / 3)
  162.                 {
  163.                     throttle = -1f;
  164.                 }
  165.             }
  166.         }
  167.         else //this input is for the Unity editor
  168.         {
  169.             //Use the Keyboard for all car input
  170.             horizontal = Input.GetAxis("Horizontal");
  171.             throttle = Input.GetAxis("Vertical");
  172.         }
  173.     }
  174.  
  175.     void CarPhysicsUpdate()
  176.     {
  177.         //grab all the physics info we need to calc everything
  178.         myRight = carTransform.right;
  179.  
  180.         // find our velocity
  181.         velo = thisRigidbody.velocity;
  182.  
  183.         tempVEC = new Vector3(velo.x, 0f, velo.z);
  184.  
  185.         // figure out our velocity without y movement - our flat velocity
  186.         flatVelo = tempVEC;
  187.  
  188.         // find out which direction we are moving in
  189.         dir = transform.TransformDirection(carFwd);
  190.  
  191.         tempVEC = new Vector3(dir.x, 0, dir.z);
  192.  
  193.         // calculate our direction, removing y movement - our flat direction
  194.         flatDir = Vector3.Normalize(tempVEC);
  195.  
  196.         // calculate relative velocity
  197.         relativeVelocity = carTransform.InverseTransformDirection(flatVelo);
  198.  
  199.         // calculate how much we are sliding (find out movement along our x axis)
  200.         slideSpeed = Vector3.Dot(myRight, flatVelo);
  201.  
  202.         // calculate current speed (the magnitude of the flat velocity)
  203.         mySpeed = flatVelo.magnitude;
  204.  
  205.         // check to see if we are moving in reverse
  206.         rev = Mathf.Sign(Vector3.Dot(flatVelo, flatDir));
  207.  
  208.         // calculate engine force with our flat direction vector and acceleration
  209.         engineForce = (flatDir * (power * throttle) * carMass);
  210.  
  211.         // do turning
  212.         actualTurn = horizontal;
  213.  
  214.         // if we're in reverse, we reverse the turning direction too
  215.         if (rev < 0.1f)
  216.         {
  217.             actualTurn = -actualTurn;
  218.         }
  219.  
  220.         // calculate torque for applying to our rigidbody
  221.         turnVec = (((carUp * turnSpeed) * actualTurn) * carMass) * 800f;
  222.  
  223.         // calculate impulses to simulate grip by taking our right vector, reversing the slidespeed and
  224.         // multiplying that by our mass, to give us a completely 'corrected' force that would completely
  225.         // stop sliding. we then multiply that by our grip amount (which is, technically, a slide amount) which
  226.         // reduces the corrected force so that it only helps to reduce sliding rather than completely
  227.         // stop it
  228.  
  229.         actualGrip = Mathf.Lerp(100f, carGrip, mySpeed * 0.02f);
  230.         imp = myRight * (-slideSpeed * carMass * actualGrip);
  231.  
  232.     }
  233.  
  234.     //this controls the sound of the engine audio by adjusting the pitch of our sound file
  235.     void EngineSound()
  236.     {
  237.         myAudioSource.pitch = 0.30f + mySpeed * 0.025f;
  238.  
  239.         if (mySpeed > 30f)
  240.         {
  241.             myAudioSource.pitch = 0.25f + mySpeed * 0.015f;
  242.         }
  243.         if (mySpeed > 40f)
  244.         {
  245.             myAudioSource.pitch = 0.20f + mySpeed * 0.013f;
  246.         }
  247.         if (mySpeed > 49f)
  248.         {
  249.             myAudioSource.pitch = 0.15f + mySpeed * 0.011f;
  250.         }
  251.         //ensures we dont exceed to crazy of a pitch by resetting it back to default 2
  252.         if (myAudioSource.pitch > 2.0f)
  253.         {
  254.             myAudioSource.pitch = 2.0f;
  255.         }
  256.     }
  257.  
  258.     void FixedUpdate()
  259.     {
  260.         if (mySpeed < maxSpeed)
  261.         {
  262.             // apply the engine force to the rigidbody
  263.             thisRigidbody.AddForce(engineForce * Time.deltaTime);
  264.         }
  265.         //if we're going to slow to allow car to rotate around
  266.         if (mySpeed > maxSpeedToTurn)
  267.         {
  268.             // apply torque to our rigidbody
  269.             thisRigidbody.AddTorque(turnVec * Time.deltaTime);
  270.         }
  271.         else if (mySpeed < maxSpeedToTurn)
  272.         {
  273.             return;
  274.         }
  275.         // apply forces to our rigidbody for grip
  276.         thisRigidbody.AddForce(imp * Time.deltaTime);
  277.     }
  278. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement