Unity3D – Drivable Vehicle – JavaScript – Super Easy

Create a scene with:

– (parent) CarBody (Box Object) -> Add Rigid Body -> Mass 200
– (child) CarWheelFR (Empty Object) -> Add WheelCollider
– (child) CarWheelFL (Empty Object) -> Add WheelCollider
– (child) CarWheelRR (Empty Object) -> Add WheelCollider
– (child) CarWheelRL (Empty Object) -> Add WheelCollider

CarBody, add the script:


#pragma strict

// Assign in Inspector
var CarWheelFR : WheelCollider; // Front Right
var CarWheelFL : WheelCollider; // Front Left
var CarWheelRR : WheelCollider; // Rear Right
var CarWheelRL : WheelCollider; // Rear Left

var Speed: float = 10; 
var Breaking: float = 20; 
var Turning: float = 20; 

function Start () {
}// END Start

function Update () {
	// This code makes the car go foward and backward - notare che è a trazione posteriore
	// simulate the whell rotation - spinta
	CarWheelRR.motorTorque = Input.GetAxis("Vertical")*Speed; // arrow up / down
	CarWheelRL.motorTorque = Input.GetAxis("Vertical")*Speed;
	
	// reset the variable, if you miss this code 'CarWheelRR.brakeTorque = Breaking;' for ever after get Space key button
	CarWheelRR.brakeTorque = 0;
	CarWheelRL.brakeTorque = 0;
	
	// This code makes the car turn
	// simulate the steer - sterzata
	CarWheelFR.steerAngle = Input.GetAxis("Horizontal")*Turning; // arrow left / right
	CarWheelFL.steerAngle = Input.GetAxis("Horizontal")*Turning;
	
	if (Input.GetKey(KeyCode.Space))
	{
		// simulate the brake, frenata
		CarWheelRR.brakeTorque = Breaking;
		CarWheelRL.brakeTorque = Breaking;
	}
	
}// END Update

Assign in Inspector var CarWheelFR CarWheelFL CarWheelRR CarWheelRL

Play

For italian people: come funziona?
1. Monto l’auto con il corpo e le ruote, imparentando le ruote a CarBody, come nella realtà
2. Con l’input da tastiera sfrutto le proprietà del Collider WheelCollider: .motorTorque .steerAngle .brakeTorque

Vedi API a: http://docs.unity3d.com/ScriptReference/WheelCollider.html