duck

Wheel script

Dec 20th, 2013
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.09 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Wheel : MonoBehaviour {
  5.  
  6.     float spinAngle = 0;
  7.  
  8.     // Update is called once per frame
  9.     void Update () {
  10.    
  11.         // assume the wheel art (the hub) is the only child
  12.         Transform hub = transform.GetChild(0);
  13.        
  14.         // get wheel collider reference as correct type:
  15.         WheelCollider wheel = collider as WheelCollider;
  16.        
  17.         // *6 converts RPM to Degrees per second (i.e. *360 and /60 )
  18.         spinAngle += wheel.rpm * 6 * Time.deltaTime;    
  19.        
  20.         // rotate hub according to spin and steering
  21.         hub.localRotation = Quaternion.Euler( spinAngle, wheel.steerAngle, 0 );
  22.        
  23.         // use a raycast to detect current spring position
  24.         RaycastHit hit;
  25.         if ( Physics.Raycast ( transform.position, -transform.up, out hit,  wheel.suspensionDistance + wheel.radius ) ) {
  26.             // wheel is touching the ground
  27.             float springPos = -(hit.distance-wheel.radius);
  28.             hub.localPosition =  Vector3.up * springPos;
  29.            
  30.         } else {
  31.             // wheel is off the ground, use full spring distance
  32.             hub.localPosition =  -Vector3.up * wheel.suspensionDistance;
  33.            
  34.         }
  35.        
  36.     }
  37. }
Add Comment
Please, Sign In to add comment