duck

duck

Feb 8th, 2011
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.09 KB | None | 0 0
  1. // extroadinarily simple car behaviour
  2. // robotduck 2011
  3.  
  4. using UnityEngine;
  5. using System.Collections;
  6.  
  7. public class Car : MonoBehaviour {
  8.  
  9.     public float maxSpeed = 100;
  10.     public float enginePower = 20;
  11.     public float minTurnForce = 0.1f;
  12.     public float maxTurnForce = 0.6f;
  13.     public float lateralGrip = 3;
  14.  
  15.     bool onGround;
  16.     Vector3 oPosition;
  17.     Quaternion oRotation;
  18.     float h,v;
  19.    
  20.     void Start () {
  21.         oPosition = transform.position;
  22.         oRotation = transform.rotation;
  23.         collider.material.dynamicFriction = 0;
  24.         collider.material.staticFriction = 0;
  25.         rigidbody.angularDrag = 2;
  26.         rigidbody.drag = 0.1f;
  27.     }
  28.    
  29.  
  30.     void OnCollisionStay(Collision col)
  31.     {
  32.         if (Vector3.Angle(transform.up, Vector3.up) < 65)
  33.         {
  34.             onGround = true;
  35.         }
  36.     }
  37.  
  38.     void FixedUpdate()
  39.     {
  40.         if (onGround)
  41.         {
  42.             Vector3 localVelocity = transform.InverseTransformDirection(rigidbody.velocity);    
  43.            
  44.             float currentSpeed = localVelocity.z;
  45.             float inverseSpeedFactor = Mathf.InverseLerp( maxSpeed, 0, Mathf.Abs(currentSpeed) );
  46.             float accelPower = enginePower * inverseSpeedFactor;
  47.            
  48.             Vector3 accelForce = transform.forward * accelPower * v;
  49.             Vector3 gripForce = -transform.right * lateralGrip * localVelocity.x;
  50.             Vector3 sumForce = accelForce + gripForce;
  51.             Vector3 turnTorque = currentSpeed * transform.up * h * Mathf.Lerp(minTurnForce, maxTurnForce, inverseSpeedFactor);
  52.            
  53.             rigidbody.AddForce( sumForce );
  54.             rigidbody.AddTorque( turnTorque );
  55.         }
  56.         onGround = false;
  57.     }
  58.  
  59.     void Update () {
  60.         if (Input.GetKeyDown("r")) { Reset(); }
  61.         v = Input.GetAxis("Vertical");
  62.         h = Input.GetAxis("Horizontal");
  63.     }
  64.  
  65.     void Reset()
  66.     {
  67.         transform.position = oPosition;
  68.         transform.rotation = oRotation;
  69.         rigidbody.velocity = Vector3.zero;
  70.         rigidbody.angularVelocity = Vector3.zero;
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment