Unity3D Car Tutorial
For a long time there have been topics on the Unity3d Forum asking about how to set up a car rig, there don’t seem to be many good tutorials out there, so I decided to write one of my own that will hopefully explain some of it for you.
Step 1 : Importing the Game Object.
The first step in creating a car setup is to set up the model in the editor so that it contains all of the necessary components. When you create a car model in your 3D modeling program (I’m using Maya), you want to make sure that you have the body, and all four wheels of the car modeled and loaded into Unity. You can have extra components, but it becomes increasingly confusing the more objects you’re dealing with. I would only recommend having more if you were building a game that required the car to have break away panels or some sort of damage system.

Here you can see the basic setup I’m using. I grouped all of the wheels inside of one object so that I can easily hide them in the hierarchy.
Step 2 : Attaching the Physics Components
First, attach a rigidbody to your car object. click on Component/Physics/Rigidbody in the menu. This will make the car model a rigidbody, making it a part of the Unity physics environment. In order to have it properly react to collisions and behave like a car, we need to attach the colliders.
I generally create an empty game object, and make sure that the position and rotation are set to (0,0,0). Rename this “Colliders”, this will serve as a container for all of the colliders that will be applied to the car. Then, create a few game objects and position them inside of this object. Then select them and click Component/Physics/BoxCollider in the menu. This will allow you to approximate the general shape of the car, while still keeping it simple.
NOTE: I generally create colliders as separate child objects of the main body, this way I can have multiple colliders in the general shape of the car. You could use a mesh collider for this, but mesh colliders do not work well for objects moving at high speeds.

In order to make the car behave properly, you can use the Unity3d built in Wheel Collider components. These are essentially extensions of the physics engine that use a raycast to determine the distance to the ground, then they apply a force on the rigidbody based on the compression of the “spring”.
Create another empty game object, just like you did for the colliders, and name this “WheelColliders”. You could put this in the “Colliders” object, but I find it easier to organize them separately. Next, place four empty objects in this container and select Component/Physics/WheelCollider in the menu. This will attach wheel colliders that can be configured to behave like real wheels. Position these colliders so that they are about where they should be on your car. They are invisible, so you can put them in slightly different places, but try to get them as accurate as possible.

NOTE : Wheel Colliders have a property called “Radius” as well as one called “Suspension Distance”, this determines the radius and spring length of the virtual wheel in the physics engine. You will need to adjust these property so that it closely matches the actual radius and suspension distance of the wheel in your model.
Step 3 : Configuring the Physics Setup
Now that you have all of the parts set up, you need to tweak them so they work together properly. I generally model my vehicles off of existing real world cars. This is a safe way to ensure that your car behaves relatively well.
There are three key factors you will need to set.
- the vehicle mass
- the suspension spring and damping
- the tire friction
Starting with the simplest of the three, vehicle mass. I generally set the mass of my vehicles to a value around 1000-2000 kilograms. Depending on how you want your car to behave. You can use any value you like, but if you’re going for a realistic setup, I would recommend staying within these values. To set the mass, select your base car object, and look in the inspector. There should be a tab for “Rigidbody”, inside of this tab, there is a property called mass. Enter the chosen value, and press enter. Remember, all units in the physics engine are in Metric, so this value will be in kilograms.
NOTE : if you would like to convert English units to Metric, simply type it into Google and Google Calculator will automatically convert it for you.
Now to configure the wheel colliders. You will need to do this to all of the colliders, so select them one at a time and enter the values you like.
The suspension spring tab will let you set the spring values. These are important for making your car suspension behave in a realistic manner, and not just throwing your car across the map. Depending on the mass of your car, you will need to adjust the spring. Generally a value between 2000-5000 will do for a medium-weight vehicle as long as you set the damping value properly. Suspension damping slows the rate of spring extension. It prevents the springs from oscillating back and forth. I used a value of 50 in this example, but you may need more if the length of the suspension is set longer.
Then you need to tweak the forward and sideways friction of the wheel. Forward friction determines the amount of friction on the wheel when rolling in the direction it’s facing, Sideways friction determines the amount of friction that prevents the wheel from sliding sideways. If you would like to know more about how these values work, look them up in the Unity Reference Manual here
http://unity3d.com/support/documentation/Components/class-WheelCollider.html
I would not recommend changing the asymptote values until you know exactly how they work, it’s much easier to change the “Stiffness” value. This is essentially a multiplier for the curve, when set lower, it decreases both values linearly. You will want this value set fairly low, generally less than 0.1 if you want your car to slide nicely. If the sideways friction stiffness is set too high, you may have some stability issues, the car will stick to the road so much, that when you try to turn at high speeds, your car will quite literally roll off into space.
Step 4 : Writing a Control Script
Now that we have the car set up in the editor, we can proceed to write the script to control it. Because I want this car to behave like a real race car, the script uses a system to simulate different gears, Each with a different gear ratio.
Unity wheel colliders are simple to use, and allow the user to easily set an engine torque value to power the wheels, but how do we know what to set this value to?
What I do, is specify a maximum engine Torque, maximum and minimum engine RPM, and an array of gear ratios. A gear ratio specifies how many rotations the engine makes, per rotation of the wheel. Simply put, it allows the wheels to spin at higher and higher speeds while still maintaining a constant engine RPM. The car must switch to a higher gear ( a gear with a lower ratio ) to maintain speed without the engine reaching it’s maximum possible speed.
So, because we have the wheel RPM ( it’s given by the wheel collider objects ), we can determine the engine RPM by multiplying the wheel speed by the ratio of the current gear. Using this we can determine what gear the engine should be in.
- If the calculated engine speed is greater than the maximum engine RPM, loop through all of the gears, checking to see whether the engine RPM multiplied by that gear ratio is less than the maximum engine RPM, if it is, then switch to that gear. This is essentially saying, if the engine is going too fast, make it so it isn’t.
- The same goes for downshifting, if the engine is going too slow, loop through all of the gears from highest to lowest, checking if it’s within the acceptable engine range.
Let’s review. Now we have a value for the engine RPM, and our script will automatically switch gears if it is higher or lower than it should be. Now we just need to apply a torque to the wheels depending on the gear.
The torque applied to the wheels should be the maximum engine torque divided by the gear ratio of the current gear. This will make it so that the torque applied by the engine increases as you shift up, and decreases as you shift down.
In order to make the car controlled by the player, just multiply the torque on the wheels by the input value, if you use “Input.GetAxis()”, it will work perfectly. To make the car steer, you can just set the steer angle of the wheels to a base value multiplied by the input value.
Step 5 : AI
For most racing applications, a simple waypoint AI system works wonderfully. The user initially sets up a series of points, in key locations around the track. The car will then cycle through these points, steering itself towards the next point in the list, once it gets there, the process simply repeats. This method is effective and easy to use because it eliminates all potential path finding problems and allows the user to define exactly how they want the car to move.
The way this will be done is with a simple series of Game Objects, each in key locations around the track, the car will then have a variable for the root transform, which it will search through when the game first runs. From this hirarchy the AI will simply create an array of vectors. Using transforms in this way allows the user to reposition waypoints during runtime for all AI controlled vehicles, allowing them to easily tweak the way the AI controls the car.
First, set up an empty game object by selecting the Create Empty option in the Game Object menu. Then, using the inspector window, rename this object “Waypoints”. This will be used as a container for all of the other waypoints, just to make it easier to manage.
NOTE : Ensure that your “Waypoints” container object is at a position and rotation of (0,0,0)
Next, create another empty game object, name it “Waypoint_0″, and drag-and-drop it inside the “Waypoints” container. ( These game objects don’t need to have any components attached because we are only using their positions so they only need to have the default “Transform” component.)
Position this waypoint a little ways ahead of the starting line for your course, and duplicate it, renaming the copy “Waypoint_1″ and position the copy along the path of the course, continue this process placing the points at regular intervals, making sure to give them numerically increasing names until you reach the finish line or come back to the start line. (Because these points are automatically read into the AI script, you want to keep the same naming convention).
OPTIONAL SECTION
One thing I reccomend doing is setting up a gizmo ( a small editor icon ) so that you can see the location of all of your waypoints in the editor. Make a simple script called “DrawWaypointGizmos”. Then, write the following code…
function OnDrawGizmos () {
var waypoints = gameObject.GetComponentsInChildren( Transform );
for ( var waypoint : Transform in waypoints ) {
Gizmos.DrawCube( waypoint.position, Vector3.one );
}}
Essentially what this does, is finds all of the transform components in the current game object and all of it’s children, and draws a nifty little cube in their place. Just attach this script to the “Waypoints” container, and you will be able to see all of it’s transforms.
Ok, we have the waypoints set up, so now we need to make an AI script. Lucky for us, the only thing the AI has to do differently than the player is decide which way to turn the wheels, instead of having user input. Because the function we are using to recieve user input simply returns a value from -1.0 to 1.0, we can just replace the “Input.GetAxis()” function, with a variable, then in another function, we can just set that variable to any value between -1.0 and 1.0 and the AI car will steer as though it were controlled by a player.
Duplicate the “Car_Script” asset and open it in the script editor. Up at the top where we define variables, add a new line. This line will define a private variable called “waypoints”, and set it’s type to be an array. Next, define another private variable, this time with an integer called “currentWaypoint” with a default value of 0, then assign a variable called “waypointContainer” as a type “GameObject”. The script will find the waypoint transforms by searching through the children of this gameObject. Lastly, define two new private floats called “inputSteer” and “inputTorque” These will be the variables we are substituting for player input.
The top of your script should now look something like this…
var FrontLeftWheel : WheelCollider;
var FrontRightWheel : WheelCollider;
var GearRatio : float[];
var CurrentGear : int = 0;var EngineTorque : float = 600.0;
var MaxEngineRPM : float = 3000.0;
var MinEngineRPM : float = 1000.0;
private var EngineRPM : float = 0.0;var waypointContainer : GameObject;
private var waypoints : Array;
private var currentWaypoint : int = 0;private var inputSteer : float = 0.0;
private var inputTorque : float = 0.0;
Now, create a new function called “GetWaypoints”, and inside, write
var potentialWaypoints : Array = waypointContainer.GetComponentsInChildren( Transform );
waypoints = new Array();
for ( var potentialWaypoint : Transform in potentialWaypoints ) {
if ( potentialWaypoint != waypointContainer.transform ) {
waypoints[ waypoints.length ] = potentialWaypoint;
}
}
all this simple function does is take in a source container, and takes all of the transforms in it and all its children. Then, it loops through those possible waypoints, and determines whether or not they are the source container. If they’re not, it adds them to the waypoint array. We need to do this because otherwise it would treat the container as another waypointa and the cars would steer off the road. Now, just call this function inside the “Start” function of your AI script. This will automatically compile a nice list of waypoints for later use.
Now, make a function called “NavigateToWaypoint”. Inside this function, we will put all of the code to change the input steer and torque values. The way we will do this, is by finding the position of the waypoint relative to the car, that way we can find out how far on either side of the car the point is. You can do this using the “TransformPoint()” function, giving you the location of any point relative to the rotation and position of the current transform.
The line should look something like this…
var RelativeWaypointPosition : Vector3 = transform.InverseTransformPoint( Vector3( waypoints[currentWaypoint].position.x, transform.position.y, waypoints[currentWaypoint].position.z ) );
NOTE : the reason I’m using a new Vector3 instead of the straight waypoint position is because I want the vehicle to disregard all vertical input.
Now we can simply set the steer angle to the relative position in the X axis, divided by the relative position magnitude. This will give us a value from -1 to 1, 0 being when the object is straight ahead, -1 and 1 being when the waypoint is perfectly parallel with the car.
The input torque value will be a little more complicated, we want the car to accelerate all the time except for when it’s turning very sharply. Using an if statement, we check if the absolute value of the steer angle is less than 0.5, if it is then set the input torque to the relative position on the z axis divided by the magnitude of the relative position much like the steer input, (You can also subtract the absolute value of the steer angle, just to make it a little better around corners). If the steer value is not below 0.5, simply set the input torque to 0.
The last thing we need to add is the code to cycle through waypoints. Just make an if statement that checks if the magnitude of the relative waypoint position is less than a tolerance value, (I generally use 10 or 15), then increase the “currentWaypoint” variable, then check if “currentWaypoint” is greater than or equal to the number of waypoints in the array, if it is, then set it to 0. This will make the track loop, once it reaches the final waypoint, it will jump to the first one again.
The final function should end up looking like this…
var RelativeWaypointPosition : Vector3 = transform.InverseTransformPoint( Vector3( waypoints[currentWaypoint].position.x, transform.position.y, waypoints[currentWaypoint].position.z ) );
inputSteer = RelativeWaypointPosition.x / RelativeWaypointPosition.magnitude;
if ( Mathf.Abs( inputSteer ) < 0.5 ) {
inputTorque = RelativeWaypointPosition.z / RelativeWaypointPosition.magnitude – Mathf.Abs( inputSteer );
}else{
inputTorque = 0.0;
}if ( RelativeWaypointPosition.magnitude < 15 ) {
currentWaypoint ++;if ( currentWaypoint >= waypoints.length ) {
currentWaypoint = 0;
}
}
Now all you have to do is call this function in the update loop, and replace the “Input.GetAxis()” function calls with the “inputSteer” and “inputTorque” values, and you should have an AI that drives around your track.
This code is for a basic waypoint based AI, so there might be some problems with navigating particularly tricky corners, or changing directions very quickly, but as long as your course is relatively large, and you don’t expect any 270 degree hairpin turns, I think it will work very well.
Step 6 : Making it all Look Nice
Now, we have a car that drives around, the only problem is that it still isn’t very cool without sound effects and spinning wheels. In order to make engine sounds, we can attach an audio source by selecting our car and going into the menu and selecting Components/Audio/AudioSource This will create a source for our sound so we can play it. Select the body of your car, and open the new Audio Source tab, inside there should be a couple of options you will need to modify. First, drag and drop the sound you would like the car to play as the engine roar into the slot. Next, make sure that you check the “Loop” and “Play on Awake” boxes, this will ensure that your sound will play constantly as soon as you start.
NOTE : For the engine sound, we will be automatically adjusting pitch, make sure your sound loops and remains at a constant pitch all the way through.
Now that we have the audio set up, we need to modify it to sound cool. Go into your car script, and add a new line. We want the engine sound to increase in pitch as the rpm of the engine increases. This way, the sound will be higher when the car is accelerating, until it switches gears when it will jump down suddenly. You have an engine RPM set up, as well as a maximum engine RPM, so why not just divide one by the other? With division, you get a value between 0 and 1, perfect for modifying pitch.
So the new line in your script should look something like this…
audio.pitch = Mathf.Abs(EngineRPM / MaxEngineRPM) + 1.0 ;
NOTE : I added 1.0 because I wanted the engine idle pitch to be the original pitch of the sound, and the highest pitch to be twice that.
Now, on to the wheels. Basically, we want the wheels to be at the orientation of the car, but rotated around the X and Y axis, so that they turn when they’re in contact with the ground. The easiest way to do this, is to align the wheels with the suspension and combine the rotation of the car by the rotation of the wheel. To position the visible wheel, first create a Javascript. Go to the Asset menu and select Create/Javascript. Now, as I explained earlier, WheelColliders work by projecting a ray downward and finding the distance to the ground. We can repeat this and find the position of the wheel. Basically, call a Physics.Raycast() and place the wheel where the ray contacts the ground, then pull it back up along the suspension by the radius of the wheel. This will make it so that the actual contact point of the wheel is on the ground and not the center of it.
The code should look something like this.
var CorrespondingCollider : WheelCollider;
function Update () {
var hit : RaycastHit;
var ColliderCenterPoint = CorrespondingCollider.transform.TransformPoint( ColliderCenterPoint.center );if ( Physics.Raycast ( ColliderCenterPoint, -CorrespondingCollider.transform.up, hit, CorrespondingCollider.suspensionDistance + CorrespondingCollider.radius ) ) {
transform.position = hit.point + (CorrespondingCollider.transform.up * CorrespondingCollider.radius);
}else{
transform.position = ColliderCenterPoint + CorrespondingCollider.transform.up * (CorrespondingCollider.suspensionDistance – CorrespondingCollider.radius);
}
}
Now that the wheels are positioned where they should be, we need to set their rotation. This is very easy. Define a private variable in your script called “RotationValue”, this will be the value ( in degrees ) for the wheel rotation around the axle. Now, to combine the wheel’s rotation with that of the wheel collider, you’d normally have to venture into quaternion math, but thankfully, Unity does that for us =). Just define the rotation of the wheel as a quaternion and multiply it with the rotation of the wheel collider.
The last step is to increment RotationValue, the wheel colliders conveniently have a value called rpm, so we just have to convert this to degrees per second and add it to rotation value.
The code should look something like this…
transform.rotation = CorrespondingCollider.rotation * Quaternion.Euler( RotationValue, CorrespondingCollider.steerAngle, 0 );
RotationValue += CorrespondingCollider.rpm * ( 360/60 ) * Time.deltaTime;
Now just stick this script on the visible wheels and attach the corresponding collider for each wheel, and now they should work properly.
Now, the burning question, “How do I effects when my car slides around?” Wheel colliders have a wonderful function called GetGroundHit. A ground hit contains all of the information the wheel collider has about it’s speed relative to the ground, using this we can check slip values! We can assign a prefab object to be created when the wheels slip, then check the ground hit, if they are slipping, then instantiate the prefab. This is a great way to make smoke, or activate a trail renderer to make tire skid marks.
I generally make a separate game object for each wheel and attach a trail renderer from the Component/Particles/TrailRenderer menu item to each of them, then if the corresponding wheel is slipping, I just enable that renderer. This is an easy way to make short tire marks on the ground, and it looks pretty good!
The code should look like this
var CorrespondingHit : WheelHit;
CorrespondingCollider.GetGroundHit( CorrespondingHit );if ( Mathf.Abs(CorrespondingHit.sidewaysSlip) > 0.5 ) {
Instantiate( SlipPrefab, transform.position, Quaternion.identity );
TireTrailRenderer.enabled = true;
}
That pretty much sums it up. I hope this tutorial has helped, You can always contact me at www.maxwelldoggums@gmail.com if you need any more advice. The complete project is avaliable for download at the bottom of the page, and all of the values I used for the parameters in the scripts are listed below. Happy driving!
I modeled my tutorial car after an Audi R8, the values in the example project are as follows.
RIGIDBODY VALUES
- Mass : 1600 kg
WHEEL VALUES
- Suspension Distance : 0.2 m
- Wheel Radius : 0.4 m
- Suspension Spring : 5500 N
- Forward Friction Stiffness : 0.092
- Sideways Friction Stiffness : 0.022
SCRIPT VALUES
- Engine Torque : 600 N*M
- Max Engine RPM : 3000
- Min Engine RPM : 1000
GEAR RATIOS
- 1st Gear : 4.31 : 1.0
- 2nd Gear : 2.71 : 1.0
- 3rd Gear : 1.88 : 1.0
- 4th Gear : 1.41 : 1.0
- 5th Gear : 1.13 : 1.0
- 6th Gear : 0.93 : 1.0
The complete project and scripts are avaliable for download
10:57 pm on August 5th, 2009
Very good tutorial! Using this as a base, I can slightly tweak somethings to fit my own project! Thanks a ton!
11:16 pm on August 5th, 2009
That’s some great tutorial! Maybe in the next one you can tell us how to make the wheels turn accordingly to the car motion, as well some motor sound that changes accordingly to the gear, brake marks on ground, etc. =)
12:04 am on August 6th, 2009
Hi Ted,
You’ll be happy to know that the motor sound already changes depending on the gear. It’s not in the tutorial, but the script in the project file already supports it, I also have a script to make the wheels rotate, and my wheel alignment script makes skid marks on the ground too…
I’ll go ahead and update the tutorial =)
5:28 am on August 6th, 2009
thanks!
1:35 pm on August 6th, 2009
Amazing, really. This is the best car controller i have ever seen on the Unity community, and it’s free. Leave some PayPal address for donations, man! =)
I’m waiting for your updates with nice little features for the car controller. Seeing “advanced” stuff like skid marks and others would be great.
11:31 pm on August 9th, 2009
Is it just me or the new version of the project has different car physics? I mean… it’s really good as it was in the first version!
12:29 am on August 10th, 2009
no, the vehicle physics should be the same, I only added comments, fixed a bug, and changed the input function. What do you notice differently?
8:51 am on August 11th, 2009
Excelente tutorial, muy bueno, en unityspain estamos buscando este tipo de tutoriales para compartir a las demás personas que están aprendiendo a desarrollar videosjuegos.
Me llamo Jorge Aldana y soy el editor de la primera revista digital de Unity3d en español y con David Callao estamos construyendo una comunidad de hispanos desarrolladores de juegos en unity3d.
Esta revista la pueden descargar en:
http://www.unityspain.com/Revista/
Gracias
Jorge Aldana
— (run through Google translate)—
Excellent tutorial, very good, we are looking at Unity Spain these tutorials to share with others who are learning to develop videogames.
My name is Jorge Aldana and I am the editor of the first digital magazine in Spanish and Unity3d David Callao are building a community of game developers in Hispanic Unity3d.
This magazine can be downloaded at:
http://www.unityspain.com/Revista/
Thanks,
Jorge Aldana
12:30 pm on August 11th, 2009
Hi Andrew, i want to contact you to talk about translating your tutorial. Please contact me at webmaster @unityspain.com
11:56 am on August 14th, 2009
Awesome stuff. Someone has taken time to sit down and write an amazing car tutorial for Unity. awesome job!!
10:15 pm on August 18th, 2009
Very Good,thand you
9:04 am on August 21st, 2009
Hi – this is a very good tutorial. I have tried several times to add my own car exactly as shown and in your download. It’s a computer controlled car.
I’ve definitely got everything set up the same. But I get these errors:
IndexOutOfRangeException: Array index is out of range.
AICar_Script.Update () (at Assets/Scripts/Car Control/AICar_Script.js:63)
and
UnassignedReferenceException: The variable CorrespondingCollider of ‘WheelAlignment_Script’ has not been assigned. This happened in the game object “Wheels”.
You probably need to select the “Wheels” in the hierarchy and assign the CorrespondingCollider variable of the WheelAlignment_Script script in the inspector.
WheelAlignment_Script.Update () (at Assets/Scripts/Car Control/WheelAlignment_Script.js:14)
Any ideas?
4:35 pm on August 21st, 2009
Hi Mark.
The first error message you are getting is because of the AI script. Make sure that all of your waypoints are named in a numerically increasing way, such as “Waypoint_1″. Then make sure to drag the gameObject your waypoint transforms are stored in into the Waypoint Container slot in the AI script. If they are not, the AI script can not determine where to go next, and will complain that the first waypoint does not exist.
The second problem is answered in the error message you got. All of the visible wheels in my tutorial have a script attached called “AlignWheels_Script”. This script will align a wheel to a collider assigned to the “Corresponding Collider” variable so that it turns and bounces correctly with the suspension. In order for the script to work however, you will need to assign the Corresponding Collider variable. For all of the visible wheels on your car, drag the corresponding Wheel Collider into the Corresponding Collider slot. This will set the wheel for each wheel model to follow and should fix the problems with the script.
I hope that helps,
-Andrew
9:53 am on August 23rd, 2009
Hi guys,
can someone tell me how to correctly rescall and reset the setup? I mean – I will make a truck racing game but I can’t figure this whole thing out…i rescaled the whole game object (car) x5, i set the weight x5… but the car acts strange! it is to heavy to drive or it seams that it has no weight (it flyse when it touches something)
can any body tell me how to fix xuch issues?
10:57 am on August 23rd, 2009
Hello Sim,
A reader recently informed me that the Unity documentation states that the physics engine is more stable when working with smaller masses, so perhaps you should try reducing the mass of your vehicle to a smaller value, like 10 or 100. You would need to tweak the torque settings, but it might work a lot better. Also, you can increase the stability of a vehicle by lowering its center of gravity. In the first few lines of the demo script, there is a line that sets the rigidbody’s centerOfMass.y property to be -1.5, this makes the car much more stable and much less likely to fly away when you’re driving.
Try that and see if you can get any better results,
Hope that helps,
-Andrew
1:59 pm on August 23rd, 2009
How do I alter the Driving script to make the car follow an object and adjust rmps based on the rigidbody’s velocity rather than the player input? I tried waypoints ai but need more precise control over steering. Is there a way to make waypoints more precise or to adjust script so Engine rpms/Gear shifting is based on velocity of the car? I am still trying to figure it out but any help would be appreciated! Thx!
2:01 pm on August 23rd, 2009
..I already have my car following an object which is following a spline path but engine is constant idle rmps so I’m trying to get input to be based on magnitude of velocity of car not on waypoints or player input . Sorry if not so clear!
6:18 am on August 24th, 2009
Hello, Its a nice tutorial, however i tried to make it, and i could make it work. Any ideas, When i attach the wheel scripts it just dissembles all my car. And i would really like to know how i can get Ai working too. I saw your project, and it looks and works great. But for some reason mine doesn’t work.
9:24 pm on August 24th, 2009
Hi Andreas,
I think the problem with the wheels, is that the pivot point of your model is not in the center of the wheel, so when it spins, the wheels just fly out from under the car. As for the AI, try naming your gameObjects like I did, “Waypoint_1″ ect, and make sure they are inside a gameObject that is set to the script in the “WaypointContainer” variable slot.
I hope that helps,
-Andrew
6:09 pm on August 28th, 2009
Hi, I had the same pivot problem so re exported. Here is my first go at using this. Thanks so much for making this understandable. Having a few problems getting the AI car to follow the track but that is for another day
4:57 am on September 9th, 2009
Hai Andrew,
I like your code. iam new to Unity3d and game programming as a whole, but iam doing a game in unity as a starting point. the game is a racing game that uses bicycles. i want modify your code so that it can be applied to my system. however iam finding difficult on how to modify the Car Scritpt that the player has to use to control the car’s movement. help me to change the code so that the player can move the bicycle by pressing the “up arrow” ,”down arrow”,”left arrow”. Also if you could help me on how to write the script so that the camera follows the rider as he races around the track.
I will greatly appreciate your help.
Thanks,
Chaiwa(Student at the Copperbelt University, Kitwe, Zambia)
6:03 am on September 9th, 2009
Hello Andrew,
Is my Question clear?
10:50 pm on September 9th, 2009
Sure! One thing I might recommend however, is removing the gear shifting entirely if you’re writing a bicycling game, I recommend just assuming a gear ratio of 1:1… I’m a bit curious though, my script already accepts player input using the Arrow keys… so I’m not exactly sure what you’re asking in that respect… try setting up the input settings in Unity, it’s in the Edit menu under Project Settings. As far as locking the camera to follow the rider, I suggest writing a new script that repositions the camera every frame, moving it the desired distance to the target while still maintaining the angle between the two, then you can slowly adjust the angle until it is directly behind the target. This will make a smooth transition so that when you’re turning, the camera will turn slightly slower than the target object.
I believe there is a pre-made script that does this included in the standard asset package, but you could also write another one pretty easily…
Just determine the target angle ( target.rotation.eulerAngles.y ), and the camera rotation ( transform.rotation.eulerAngles.y ), and “Lerp” one to another using Mathf.LerpAngle( currentRotation, targetRotation, 0.1 ) This will basically smoothly interpolate from one value to another, it essentially the same as saying…
value1 += ( value 2 – value 1 ) / 10;
Now, just set the camera position to it’s rotation times the vector ( 0, 0, -followDistance ) added to the target position. This will clamp the camera to the point a given distance from the target position, not allowing it to extend farther or move inward than the given range.
Lastly, you can just set the camera’s Y position to that of the target +- some value, clamping the camera at the desired height.
The built in “SmoothFollow” script has this same thing commented much better than I have here, so I suggest taking a look at that…
I hope that helps,
-Andrew
10:43 pm on October 15th, 2009
hi ,..this is a good tutorial,..but i have a problem,..why my car can’t move ? like forward, backward, turn left, n turn right? please help me…..
tnks for advance
3:15 pm on October 16th, 2009
It’s set up so that it works with the Input preferences set up in the Unity Editor. Also make sure that you’re using the Player Car script, and not the AI car script.
10:02 pm on October 16th, 2009
tnks a lot for ur respon Andrew,..
7:08 pm on October 21st, 2009
Did you reprint your tutorial here or is it just an extreme coincidence
http://www.unity3d8.com/content/awesome-unity-car-tutorial%E3%80%80unity3d%E7%AE%80%E5%8D%95%E8%B5%9B%E8%BD%A6%E6%95%99%E7%A8%8B
2:43 pm on October 30th, 2009
Is it possible to test all the waypoints to the car and then the one that is closest it chooses to go to? If it is can you show me how you would go about this. Thanks.
12:15 pm on November 2nd, 2009
I was wondering if you had, or are, developing a function for controlling turning or steering limits?
8:11 am on November 3rd, 2009
Hello Andrew again!
Thanks for your advice. it is working, but i still have a few problems with the behaviour of the camera and bicycle. when i move the bike in the forward direction, the bike passes through(or cuts through) the “humps” and other objects along the track. i want the bike to behave in such a way that it is able to detect where the track has hump or to simulate climbing a hilly track. in other words the bike should always stand on the surface of the terrain.
Please help.
THANKS
1:46 pm on November 5th, 2009
Hi Andrew,
Great job on the example project (I downloaded it and take a look), my name is Iñaki Lauret, the man behind “Ikiman” in the Unity forum, and the one responsible for 3dnemo.com.
I think you are the only one that developed a nice AI for the opponent cars. If you saw my posts in the forum you can see I’m using a totally different system for that.
I’m continuosly developing the car behavior (when my regular job permits it). Will you be interested in any collaboration?, maybe together we can find even better solutions.
If you are interested you can drop me a message in the Unity forum or directly to my contact e-mail in 3dnemo.com.
Thank you
2:50 pm on November 9th, 2009
Hai andrew!!
Would help me find a site where i can download a “free” animated 3d model of
a bicycle rider!!
i will greatly appreciate!!
12:38 pm on November 11th, 2009
Hi Andrew,
thanks for sharing this awesome tutorial. We set up our own track and vehicles and it works just fine – except we noticed that the forces work in the wrong direction. When the vehicle tuns left it leans also to the left, where it should lean to the right. Also when accelerating forward the front of the car should rise but it is tilting …
Any ideas? It seems like the “BoxCollider” is not working properly? Many thanks in advance,
Cheers
9:05 pm on November 11th, 2009
hey i’ve got a problem with my car not moving. i have the wheel colliders in the right place and set the scripts up exactly how u did but the only difference is there 3d car model. any suggestions??
6:01 am on November 13th, 2009
Hello Andrew,
this is my second comment – as the first one was surprisingly removed? Again, thanks for this excellent and very useful tutorial. I noticed that the forces on the individual cars work in the wrong (opposite) direction? When the vehicles accelerate, the nose tilts forward to the ground, when it breaks/slows down – the nose rises. When the car makes a left turn, it leanes to the left, where it should lean to the right … Any ideas on this?
Many thanks in advance!
6:09 am on November 13th, 2009
Hi Andrew again,
please forget my previous post – i found the solution myself. It seems i just have to adjust the following line in your PlayerCarScript: rigidbody.centerOfMass.y = 0;. After changing the previous value from -1,5 to 0 the car behaves just fine.
Thanks again for your detailed tutorial!
6:42 am on November 13th, 2009
Hello Andrew!
I’m having problems finding the right values for almost everything, Are there any formulas or anything to find the correct values?
I’m building my car model on Ferari F50 but unfortanly i have no idea how to set the forward’s and sideway’s fiction,
Please Help soon.
Thanks Daniel.
9:44 am on November 28th, 2009
I noticed that if a model is made up of multiple pieces that the script doesn’t seem to work (as you stated in the tutorial). My model has a right and a left side so that the textures look right, but this seems to keep this script from working. Is there a work-around for that or will I need to remodel everything?
Thanks!
11:04 am on December 7th, 2009
at first,thanks for your tutorial,but i think there is a error with your code in this tutorial,
“
var CorrespondingCollider : WheelCollider;
function Update () {
var hit : RaycastHit;
var ColliderCenterPoint = CorrespondingCollider.transform.TransformPoint( ColliderCenterPoint.center );
if ( Physics.Raycast ( ColliderCenterPoint, -CorrespondingCollider.transform.up, hit, CorrespondingCollider.suspensionDistance + CorrespondingCollider.radius ) ) {
transform.position = hit.point + (CorrespondingCollider.transform.up * CorrespondingCollider.radius);
}else{
transform.position = ColliderCenterPoint + CorrespondingCollider.transform.up * (CorrespondingCollider.suspensionDistance – CorrespondingCollider.radius);
}
}
”
make attention at the code
“
transform.position = ColliderCenterPoint + CorrespondingCollider.transform.up * (CorrespondingCollider.suspensionDistance – CorrespondingCollider.radius);
”
i think it should be
”
transform.position = ColliderCenterPoint – CorrespondingCollider.transform.up * (CorrespondingCollider.suspensionDistance);
”
the position of wheel should be ColliderCenterPoint+suspensionDistance, when the haven’t grounded .am i right?
P.S. : i am chinese,my english is very bad!
4:10 am on December 10th, 2009
Thank you, really a great halp in understanding wheel colliders! : D
10:34 am on December 27th, 2009
Any chance of a prefab example, that would be so awesome – can’t code, can’t understand it, just want to be able to make assets. I wish the prefabs were available with placeholder art to tweak as we wish, coding is not a lot of people’s things.
Thanks though, I know some more rules about unity, but I can’t do this on my own.
8:13 am on December 28th, 2009
Hi andrew, i got this message! could give me a hand on this one.
Thx !!
IndexOutOfRangeException: Array index is out of range.
PlayerCar_Script.Update () (at Assets\Scripts\Car Control\PlayerCar_Script.js:44)
2:38 am on January 3rd, 2010
Hi Andrew
Happy New Year 2010 and thank you so much for your time in this tuto.
I have got a question:
How do you get the correct array’s size (GearRatio) without initialize it?
You wrote:
var GearRatio : float[];
But for me nothing works in the right way, I’m building a new race game test from the ground, and I can’t find the way that you initialize that array, maybe a funcion or object “Awake” and initialize that array.
I write this in order to continue with your tuto:
var GearRatio : float[] = new float[6];
Well, thank you in advance
10:50 am on January 3rd, 2010
Hello Cesar,
The way I did it was in the Unity editor. If you define an array with no specific size, you can look in the object inspector and there will be a little tab for that array, you can expand it, specify a size, and enter values. I find this more useful because it allows you to specify a different number of gear ratios for different cars using the same script.
Hope That Helps,
3:12 am on January 4th, 2010
Thanks Andrew, I got it! lol
I added a “turbo speed” with:
Input.GetKey(”space”)
Everything is good and funny in the Editor Simulation, but when I chose “Build and Run” my space key doesn’t work, I’ll search for what and try to send this trick.
I’ve got 2 days in Unity3D and it rocks dude!
Thank so much Andrew, greeting from Lima-Peru.
5:27 pm on January 10th, 2010
Nice tutorial. I got the player-controlled car working, but the AI controlled car flies off into the sky and throws the ” IndexOutOfRangeException: Array index is out of range. ” error that Mark was getting. The problem is, I can’t fix it because the WaypointContainer slot doesn’t show up in the Unity editor. Any clue how I can fix it?
5:34 pm on January 10th, 2010
Wait i figured out why it flies off into the sky. I have colliders on my waypoints. whoops.
5:50 pm on January 10th, 2010
I get this error which may be preventing the script from compiling, so that the new property is uncompiled:
Assets/simpleCarAI.js(32,94): UCE0001: ‘;’ expected. Insert a semicolon at the end.
This is the line in question, which obviously contains a semicolon:
inputTorque = RelativeWaypointPosition.z / RelativeWaypointPosition.magnitude – Mathf.Abs( inputSteer );
How do I fix this?
6:14 pm on January 10th, 2010
Alright, fine. I don’t need it fixed. I’ve just downloaded the source.
9:12 pm on January 14th, 2010
Hi Andrew, im trying to use your script on the unity iphone.. there is an error occurs on the AICar_Script.js. That says Assets/AICar_Script.js(91,124):BCE0019:’position’ is not a member of ‘Object’. hope u can tell me..,
Thanks for the nice tutorial…
6:29 pm on January 19th, 2010
I would kiss you right now!!! if i aint a men….. lool.
But, by far best tut iv seen about a car game engine, i would say keep it going, but it seems that you took a pause, but i keep you in my feed nether the less.
Good work men.
9:52 am on January 21st, 2010
Hi andrew
Well i have a small problem i have my own models and i got it all running except for the wheel alignment. it rotates my wheel in a very weird way. the pivot is in the centre but it does not work as i want it to. maybe you can help me. i thought about setting the rotation axis to x but i dont know how to do it any suggestions?
7:25 pm on January 22nd, 2010
Thanks a lot – really good tutorial!
10:02 am on January 23rd, 2010
Thanks for taking the time to create this! Saved me HOURS of trial and error time!
9:50 am on February 3rd, 2010
Hi Andrew!
Nice tutorial so far!
I tried to remake this with an own car and tire model, but I got a strange issue: My back always is in the air! If I press “forward”, the wheels are on ground but after that, my car “jumps” onto the roof. Any idea where to look? I think I compared every value
Image: http://up.touny.de/img/15-48-08-auto_strange.jpg
Thanks!
5:42 am on February 4th, 2010
Nice one!
Donated $10 to get this is PDF format
Keep it up!
-Timo ‘rouhee’ Anttila
6:55 pm on February 4th, 2010
Andrew,
Thank you for the detailed tutorial. I wonder if you might have some guidance on poly counts / texture sizes for vehicles? We have hi-poly models which we want to bring into Unity games and are going to create low poly versions. Any advice here would be greatly appreciated.
4:29 pm on February 6th, 2010
Does anyone know how to run this tutorial. i press play button in unity but then nothing happen just engine sound, how to drive the car.
Thanks in advance
3:29 pm on February 18th, 2010
Im getting an error and I have no idea how to solve it.. I haven’t changed anything in the code itself.. so it must be something in my setup..
I’ve done your tutorial 3 times now.. and this is the only error I keep getting, can you help me out here?
IndexOutOfRangeException: Array index is out of range.
PlayerCar_Script.Update () (at Assets\Scripts\Car Control\PlayerCar_Script.js:44)
5:55 am on March 4th, 2010
Awesome tutorial. Its a very good reference material to begin with. Covers almost everything.
9:06 am on March 4th, 2010
Andrew,
Have you seen (or experienced) anywhere how the center of mass for a game object is calculated? Does this work off of the box colliders assigned to the rigid body? So when I make an adjustment of -1.5y, where is the reference point on the object?
If the vehicle is abnormally proportioned (cartoon-like vehicle), how can you separate the collision characteristics from vehicle handling? I want the vehicle to feel as though its edges are where it collides with other meshes, but because it is a vehicle not designed to drive in the real world, the exagerated mesh size isn’t a good reference for good handling.
Once again, your help is greatly appreciated.
- Robert
7:20 am on March 7th, 2010
when i try to run the AIcar script i get this error
position is not member of object
at these lines
var RelativeWaypointPosition : Vector3 = transform.InverseTransformPoint( Vector3(
waypoints[currentWaypoint].position.x, transform.position.y, waypoints[currentWaypoint].position.z ) );
i am not changing anything just running the project directly as i downloaded
Thanks in advance
2:37 pm on March 8th, 2010
Looks sweet.
I have a question though, could it be tweaked so the car rolls around and has very bouncy shocks… like the warthog in halo?
2:09 am on March 18th, 2010
Hi Nice That some one really helped me solve this issue.
But Can u tell me How am i not able to even rotate the wheels or the colliders even when every thing is setup properly.. Can say i copied all your values but wheels are not rotating.. Plz Help!!
10:21 am on March 23rd, 2010
Dear Andrew,
Thanks for this great tutorial. I have a problem with the wheels. After i apply the wheel collider and the script for alignment the wheels are horizontal instead of vertical and turn around the wrong axis. I know it’s a pivot problem before exporting but i just can’t get my head around it. I’m using 3D max and i made sure to center each pivot for each wheel. Can u help me?
2:51 am on April 5th, 2010
Hey, Andrew!
I was trying to do the tutorial, (With the exception with my own modeled car and wheels… which look terrible I might add but that isn’t the point)
Trying to make it function exactly like the tutorial you included, I also used the same scripts.
But when running them on my attempt, I receive this error..
IndexOutOfRangeException: Array index is out of range.
PlayerCar_Script.Update () (at Assets\Standard Assets\Scripts\Car Control\PlayerCar_Script.js:44)
Any ideas?
Thanks in advance.
12:28 pm on April 16th, 2010
Hi Andrew, don’t know if you’re still reading these comments.
Great tutorial, one of the few good car tutorials around. I am relatively new to Unity but I’ve pretty much got the car working nicely.
However, the car doesn’t seem to want to go in straight lines, veering to the right slightly. I’ve checked the wheel colliders and they may not be the problem. It goes in a straight line when the Up key is not being pushed.
Also, I’ve had a problem with the smooth follow script (was looking at the right side of the car and not the back). Swapping the x and z co-ordinates mostly solved the proble,, but the camera still looks at the car from a slight angle. The camera also occasionally flickers from a side view to back view.
You can see a video of it below
http://www.youtube.com/watch?v=f3guif_cJ6g
If you could shed any light on this, that would be great.
3:24 pm on April 18th, 2010
how do you get this working for iphone? Is there a tutorial or an easy way to do that?
7:19 pm on April 21st, 2010
THX ANDREW!! I made a tutorial in french
http://www.chrissavian.webs.com/index.htm
http://www.youtube.com/user/therealChrissavian#grid/user/97C365D53FB53BE2
7:03 pm on May 2nd, 2010
Great tutorial, any idea as to how to make this user controlled?
Thanks!
1:47 am on May 14th, 2010
Another awesome tutorial!!! Thank you so much for taking the time to not only writing the the tutorial but heavily commenting the scripts line by line. It really makes a difference!! Also I didn’t see the pdf inside the zip file like with the helicopter demo. Am I missing something? Thank you!
1:23 pm on May 15th, 2010
hello i think it’s a very nice tutorial but does it say how to move your wheels and add sounds? i didnt actually do it but i read some parts but didnt do it.. just wanted to know before i start. and i make my car with 3D max 2010 should i make the Tires and the body of the car seperate from each other and put them together in unity or should i make the entire car in 3D max and import it to unity? and the last thing should i colour it in 3D max or unity? sorry for my english (only 14 years old) and from the netherlands
thank you
11:30 am on May 23rd, 2010
The PDF is within the Unity project folder, several people have been confused with that; I’ll relocate it and post an updated project soon…
11:04 pm on June 4th, 2010
I have followed your tutorial and got it working with your vehicle. Like another commenter, I am looking at translating this into a bike program but I am having problems with the physics and cannot seem to find any advice on this process. I am a newbie to Unity and it is showing. First off, i tried to create a two wheel vehicle that spun in circles and was erratic. Then, I copied all the colliders and code from the computer cars into a a new asset with the image of a bike. I was hoping that this transfer of colliders and its settings would make the vehicle mirror the behavior of the car, but instead I get a four wheel vehicle that either turns in circle or drives off the board. I have tried to change the mass and torque also but nothing seems to help, and I am not sure why this is occuring. Thanks for any advice you may have.
6:26 am on June 13th, 2010
Thanks for this great tutorial. but i can´t find the PDF in the ZIP file.
The PDF is diferent from the information on the website?
Thank you.
5:55 am on July 11th, 2010
What a great tutorial! I think this will be my next project.
I am a student who is currently starting a Unity club with a few of the other more motivated students in our 3D program. I am learning, then teaching what I learned, then learning more, more teaching, etc. It’s a process!
I am happy to see you are still supporting questions on your tutorial. Hopefully I will not have to comment again until I give a gracious thanks for your hard work.
2:41 am on July 15th, 2010
superb tut andrew. However what would one have to change for front wheel, rear wheel and 4 wheel drive? and front and rear mounted engines?
10:16 am on July 20th, 2010
Thank you for an excellent tutorial.
4:31 pm on July 20th, 2010
great tutorial! you helped me alot
How can I calculate the speed ?
If I crash into some AI car they ome times start to drive backwards
-how to fix this?
Thank you
9:55 am on July 22nd, 2010
GREAT tutorial, but I have one question:
I edited your project a bit to add manual gear changes.
The problem I have now is that when you accelerate in highest gear, it will just drive away very fast, while in real life it wouldn’t drive at all.
How to fix this?
12:13 pm on July 22nd, 2010
@Arie: Calculating the speed is easy.
It’s (WheelCollider.rpm * 2 * Mathf.PI * WheelCollider.Radius)/60 –> this is in m/s.
Take one of the WheelColliders or take the average of multiple WheelColliders.
—————————————————————————————————-
I found also some bugs in the project:
- You forgot about axle ratio, which will multiply the gear ratio by something between 3 and 5 ( your car now can get to the speed of over 300 km/h )
- You have used Update() instead of FixedUpdate().
12:59 pm on July 26th, 2010
Hi Andrew,
I’m working wirt your AI Car script but the car with the script applied never moves.
I recieve the error of the Array being out of range but I’m sure all the waypoints have an incremental name and the parent object it’s dragged in the slot of the AIcar script. Any idea?
I have noticed if in your scene if you reset the script in one of the computer cars (RMB > Reset) it’s stop moving when playing the game while the other one keeps running, and I have a car like this one stucked, with all the scripts applied but no movement.
Thanks a lot for the tutorial and your answers
1:47 pm on July 26th, 2010
I forgot another question. When I activate the AIscript the frame rate decreases a lot. The scene runs at ~70fps while the script remains deactivated, and about 10-15 when activated
11:14 am on July 27th, 2010
Hi,
first of all, congratullations for this great tutorial.
I was exploring your scene and clonning some cars, to a total of four computer cars working fine. Then I tried to apply the scripts in my own scene and it’s working but in a weird result. The computer car follows the waypoints doing very strange movements and crashing all the time. I follow the same steps but in my case I scaled down the wheel colliders because my car is smaller than yours. Now the radius is 0.3 and the suspension distance is 0.1. Can it be the problem?
Thanks a lot
6:23 am on July 28th, 2010
Why is one of my questions still awaiting moderation, while another (posted later) is already approved?
6:08 am on August 4th, 2010
hi,
this is just great! thanks. i will be mostly using this for my indie game….
8:20 am on August 27th, 2010
Quote: – You forgot about axle ratio, which will multiply the gear ratio by something between 3 and 5 ( your car now can get to the speed of over 300 km/h )
How can this be fixed in the script?
11:47 am on September 3rd, 2010
Hello,
Like many others, I’m looking for a good tutorial that could help me to make a moto racer, but I stuck. I tried to modify the script from the car tutorial, unsuccesfully. Is anybody there can help me please ?
11:26 pm on September 19th, 2010
Great tutorial but I’m having a problem modifying it. I added a car model and set it up as per the tutorial and I used the AI car values just for testing. I try to run it and get the following:
!IsFinite(outDistanceAlongView)
UnityEditor.EditorGUIUtility:RenderGameViewCameras(Rect,Rect,Boolean,Boolean)
IsFinite(outDistanceAlongView)
UnityEditor.Handles:Internal_DrawCamera(Camera,Int32)
Assert in file ..\..\Runtime\Camera\RetainedRenderqueue.cpp at line: 335
If I remove the new car, it runs fine (editor not build), I put in the new car and get the message. I tried several different car models from various sources (created as prefabs in other projects) with same result. This sounds like a low level error not an editor level one. Any help would be great.
12:21 pm on October 11th, 2010
Hi, I am trying to work through this tutorial for a computer science class, but I have had trouble figuring out how to “Duplicate the “Car_Script” asset and open it in the script editor.” in step 5. Where the “Car_Script” located is, is a standard unity asset, was there another tutorial that you made to make it?
3:11 am on October 12th, 2010
Great detail tutorial, i wish i have found this earlier !
Thanks, man
1:32 pm on October 20th, 2010
could a motorcycle works with this tutorial??
12:28 pm on October 22nd, 2010
This was a really helpful and quick way to learn basic racing games. I’m wondering if anyone else has tried a lighter vehicle such as a go-kart? When I made the mass too low, the kart just flies around and is impossible to control. What else do I need to change to make it more realistic?
12:46 pm on October 22nd, 2010
It was the center of gravity being too low. For a smaller car, I made it -0.5 and reduced the torque as well. Still need to tweak the values more…
8:04 am on October 23rd, 2010
Hello,
Thanks for the great tutorial, i want to add wrong way detector , any ideas how to implement this ?
2:21 pm on October 27th, 2010
Hi Andrew,
Thank you for this great car tutorial. I have been through it thoroughly, and created my own project from scratch and did the tutorial.
Everything works except one thing, I cannot get an AI car to move. It just stays stationary. I have copied all car settings, and even used your original script from the
project. I cannot find what could cause this. AI Car always stands still. I have moved the waypoints around, closer/further etc but to no avail.
Any ideas?
Thanks
8:35 am on November 6th, 2010
Hello nice tutorial, very useful for my project especial for A.I, but i have an problem whit the WheelAlignment_Script, when i add this script to my wheels car the wheels comes up of my car, is not in correct possition.
The WheelAlignment_Script need to be updated, especial for auto fit wheels , to fit any wheels scale ratius, etc….
any adeas wow to?
3:11 pm on November 11th, 2010
umm this dont make sense to me is the car all one models with the wheels as seperate peaces or indavidual models files can u make that car in one file but the wheels be seperate peaces? i would like a video tutorial of all this reading it dont make sense.
4:22 pm on November 13th, 2010
What is the easiest way to convert this for iphone with using accelerometer controls instead of keyboard?
5:51 pm on November 17th, 2010
Any Updates??
A.I script need to be Updates fix bugs.
In my case i need help how to fix the problem of A.I car, when crash the A.I car run backwards.
How to A.I when crash return the correct possition?????
7:16 am on November 18th, 2010
Hi there!
i was tweaking this to my project and i came across the thing to choose constant force or adding to the variable EngineRPM to make like a nitro effect. How do i do this cuz mine wont work:
var NitroPower = 200;
//200 is just for testing purpoises (fail spelling)
if (Input.GetButtonDown(”Nitro”)){
EngineRPM += NitroPower;
when i test it nothing happens
7:17 am on November 18th, 2010
oops… the lines were :
var NitroPower = 200;
//200 is just for testing purpoises (fail spelling)
if (Input.GetButtonDown(”Nitro”)){
EngineRPM += NitroPower;
}
when i test it nothing happens
1:49 pm on November 18th, 2010
Hey man, great stuff. It seems I’m late to the party, but fashionably so. Anyway, I got the player car to work just fine but I’m having trouble with the AI controlled cars. After it hits the first waypoint it hits the brakes hard and goes in reverse. Not only that but it’s acceleration in reverse seems to be twice that of it’s forward acceleration. It’s so much that while driving in reverse the back end of the car jumps into the air!
I haven’t messed with your code too much (just modified the turn angle a bit and center of gravity) so I don’t think I jacked something up. Any idea what could be the problem? I named the waypoints and it’s container just like you did. I’ve gone over your test scene with a comb and can’t see what’s different from mine and yours.
10:12 pm on November 19th, 2010
Any one fix the A.I script, that A.I carson collision drive basck??
11:59 pm on November 22nd, 2010
ok none of this covers how to get the shocks models to ride properly from the wheel to the vehicle and react the way a shock should
9:45 am on December 19th, 2010
Hey Andrew,
I have a basic question, how do you make it in the editor so that the car’s body and wheels belong to the same model but are separate from each other in the 3d space?
Thanks
2:07 pm on February 14th, 2011
Hello Andrew!
First of all, thank you by your tutorial. I’m having trouble with my game: The game starts but the car doesn’t move at all.
IndexOutOfRangeException: Array index is out of range.
PlayerCar_Script.Update () (at Assets/Scripts/Car Control/PlayerCar_Script.js:44)
Any suggestion will be very appreciated
2:51 am on February 25th, 2011
Your tutorial has been a fantastic help with my own project, thank you.
Now I need to fumble my way through multiple AI
10:13 am on March 9th, 2011
Hi!
This tutorial is great! But I’m facing a little problem! When I press play unity says:
IndexOutOfRangeException: Array index is out of range.
PlayerCar_Script.Update () (at Assets/Scripts/PlayerCar_Script.js:44)
And my car’s wheels fall sideways on the plane, they are attached to the car, but they are just sideways! :O Hope you can help me!
2:36 am on March 22nd, 2011
Hello,
Any one help me to find out to get the Position AI car and Player Car.
Thanks in Advance
Thank you
6:58 pm on April 11th, 2011
Its a pity you cannot get out of the car and walk around FPS/3rd person style ,can taht be added to the car script easily ?
4:40 am on April 13th, 2011
very good bro
11:46 pm on April 17th, 2011
Well, I loved the tutorial – It was incredibly helpful, so I decided to implement it into the official Unity3D car physics tutorial.
Thanks! =D
PS: Here’s the thread if you’re interested – The source includes how to implement many cameras, how to rotate a steering wheel, and other little things.
http://forum.unity3d.com/threads/86148-Open-Sourced-%28Free%29-car-physics-engine-for-Unity3D-lite-YouTube-video-included!
5:26 am on May 5th, 2011
Hey Andrew, check this out,
http://forum.unity3d.com/threads/88143-Me-attempting-to-achieve-some-semi-realistic-vehicle-physics-with-wheel-colliders.?p=569376#post569376
and tell me what you think by e-mail!
10:08 am on May 10th, 2011
hello…i downloaded your file but it has steering wheel problem..please help me ..
2:37 pm on May 28th, 2011
Hi Andrew,
Any advice on what to do if the car starts driving backwards?
Thanks
7:13 am on May 29th, 2011
Silly me, you can simply check if the car is driving backwards with…
if(inputTorque < 0)
// Car driving backwards..
6:16 pm on June 28th, 2011
Hello, This tutorial has worked great, however whenever i try to drive, my vehicle goes on its front wheels, and when i turn it leans INTO the turn, off of the outside wheels. I was wondering what i could do to fix this?
7:33 pm on June 28th, 2011
Hey, I realized what I did wrong, I forgot to make separate wheel followers, as I made mine in the wheels. I also didn’t put in the ‘wheel alignment script’ however I tried to put my own wheels on the car on the completed project, I confirmed everything was the same just with different models, and they dissappear. What is wrong?
10:48 am on June 29th, 2011
Hi, I’m trying to port the AI code to c#- any chance of a hand? Email me if so, or just reply here
.
10:25 am on July 15th, 2011
I’m trying the tutorial and it’s really good. I’ve got a car in that will roll and react to physics when crashed into by another car, but I Can Not drive the car. What am I missing? I’ve set it up and believe I’ve done all the steps, but my car will not respond
to keyboard controls. Thanks for any help you can give.
6:38 pm on July 19th, 2011
Greetings,
I love the script.
I am trying to create a simple proof of concept for a car driving game … no AI cars, flat landscape, simple car design.
However, we get the following errors:
IndexOutOfRangeException: Array index is out of range.
PlayerCar_Script.Update () (at Assets/Car Control/PlayerCar_Script.js:44)
When we set EngineRPM = 100;
We get …
IndexOutOfRangeException: Array index is out of range.
PlayerCar_Script.Update () (at Assets/Car Control/PlayerCar_Script.js:57)
and then …
IndexOutOfRangeException: Array index is out of range.
PlayerCar_Script.Update () (at Assets/Car Control/PlayerCar_Script.js:58)
When we set …
FrontLeftWheel.motorTorque = 10;
and
FrontRightWheel.motorTorque = 10;
the car drives but at that slow speed.
When we increase the numbers, the car just bounces and/or fly all over the place.
Any suggestions?
Thank you in advance,
Eric
1:42 pm on July 25th, 2011
Any idea when will my question pass moderation?
4:09 pm on July 31st, 2011
Your layout is really briliant. I’ll be using something similar for my own site if you don’t mind.
11:12 am on August 4th, 2011
Hi, hope you’re still about. This was a great tutorial and everything well explained. I followed from the start and modeled my own vehicle adding your scripts etc and it works perfectly.
However…. I do have a question that was asked earlier on but I didn’t see an answer: I’m trying to make my vehicle either Rear Wheel Drive or 4 Wheel Drive… Whatever’s easier for you to explain.
I’ve tried different ways changing the script but nothing seems to work. I’m sure I’m just being silly and you’ll know the answer straight away.
Once again, thanks so much for putting up such a great tutorial and I would appreciate any help you can give me
11:31 am on August 4th, 2011
Fantastic tutorial. Any easy way to make the vehicle either Rear Wheel Drive or 4 Wheel Drive? I’ve nearly finish my full game and it’s the only thing I’m stuck on.
Once again, thank you so much for posting this tutorial, it really helped as I only do design and modeling… Programming I’m getting better at though.
3:17 pm on September 2nd, 2011
Thanks for the great tutorial! This is really helpful.
I have been playing around a bit and at this point I have a car in a simple environment. It works for the most part, there is just one thing wrong that I can’t fix. My car is really unstable, if I press forward and keep it pressed (and don’t do anything else) in a few seconds the car will tilt forward a bit and make a violent turn, like a corner hits the ground and flips it. If I use the side arrows the car turns really wobbly and makes crazy turns and spins.
For as far as I can see, I did everything just like in the tutorial, just can’t figure out what is going on here.. any ideas?
1:31 pm on September 11th, 2011
Looks good, I’m gonna print it
And try it out
3:25 am on September 13th, 2011
Hi Andrew, iv been fidgeting with the tutorial and models and iv had a serious problem.
When i attach the wheel alignment script to the wheels, the wheels get detached from the model, they start acting wierdly..when i remove it, the car is goin on smmoothly.. Am i missing something in the wheel alignment script?
1:08 pm on September 14th, 2011
I am trying to follow your car tutorial. In the very beginning when I crete a game object and rename it colliders and then Create two other Game Objects and rename them Collider1 and Collider2 I assume I put that Collider folder under the Body of the car. My question is when I select them and click Component/Physics/BoxCollider in the menu. (This will allow you to approximate the general shape of the car, while still keeping it simple.) I actually just get a box at the location 0,0,0 and nothing approximating the shape of the car. Can you possibly give me some pointers as to what I am doing wrong?
11:24 am on October 7th, 2011
Hey one question, I’m working with the project left on the web, but I have a question, I’m trying to add the parking brake to the script, in theory it is assumed that this is done by lowering the motor torque to zero or giving a high value the braketorque, but it does not work the car is advanced, I’d appreciate if you help me add the parking brake or code indicated to me that I use.
thanks beforehand.
10:00 am on October 10th, 2011
Hi
I need the code for the handbrake
8:56 am on October 11th, 2011
thanks for this tutorial! it was very informative and alot of fun.. (though i really wished it was all C#)
Step one: Delete track asset
Step two: Create a floor 1000×1000 (dont forget walls)
Step three: Child waypoints under player car, delete all but a few (or one) waypoints and center them 0, 0, 0
Step four: Duplicate computercar many many times (think i did 80 of them)
Step five: hit play, and try not to end up on the bottom of a 80 car pileup! XD
10:02 pm on October 11th, 2011
Hello admin,
I am Sanjay, a student in India, Pursuing B.A in Game Design, currently I am in the final year of my degree, I got to do a project in game design, I was in thought of design a racing level, but after all seeing your game tutorial over here, I was really impressed and inspired to do a fully functional racing game based on my own city. I am not a programmer in base, I have no clue in programming. I would like to contact you. And sandymarcus2008@gmail.com is my gmail id.please mail me, i want to speak up with you.
Thanks a lot for sharing your knowledge with us,
you have done a good job so far.
Thank you.
6:25 am on October 12th, 2011
Hello,
How can i Identify the Player and AI cars Positions ?
e.g.
1. ComputerCar
2. PlayerCar
3. ComputerCar
Thankyou
10:47 am on October 18th, 2011
Hi Andrew…great tut..
Just a quick question, I set up everything as is in the tutorial. I am setting up a test scene, my car is a cube and my wheels are cylinders. Each time I play the scene my wheels rotate 90 deg…I know it’s something to do with the wheel colliders. I’ve gone through the unity page on it…I’m dying to get this working, I hope you can help.
Regards,
Gary
12:27 pm on October 18th, 2011
…continuing on…the rotate either 90 on the x or y….
4:31 pm on November 2nd, 2011
Hi!
I’ve been following this tutorial using my own meshes, and even tho it seems to work perfectly, I got one problem.
My wheels are spinning along the wrong axis.
Now I looked it up in 3ds max to see if I had done something wrong with my pivot, however everything seemed fine.
Even in unity the pivot seems to be OK, however when I rotate my wheels manually it shows me that in the inspector it will rotate on a different axis than on the screens pivot.
Any idea on how to fix this?
Thanks in advance,
Nick
5:15 am on November 4th, 2011
awesome tutorial its good
:):):):):):) very happy to see this
but i have a doubt in the AI script when the computer car is rotated over 180 degrees.,(when i hit the car or something happened etc) that is the car front is backwards even though the car moves as it is forward side. please tell me how to rectify it. plz tell me…thank u
1:57 pm on November 10th, 2011
Hi – Great Tutorial : However, whenever i run the car on some plane : The car doesn’t run smooth and suffer from rotation as its x,y value changes. Any clue whats happening and why ?
6:01 pm on November 25th, 2011
Masterrrr… sos un groso!!!! Se agradece mucho!!!
8:48 am on December 7th, 2011
Thanks for your content. One other thing is when you are promoting your property on your own, one of the concerns you need to be cognizant of upfront is how to deal with house inspection accounts. As a FSBO supplier, the key to successfully switching your property along with saving money with real estate agent commission rates is understanding. The more you already know, the easier your property sales effort are going to be. One area where this is particularly important is inspection reports.
10:03 pm on December 13th, 2011
Can you email me man, I’m tryin to set this up with my Buick, and it won’t work, the tires just shoot off in all directions. Might it be that it doesn’t work with the new Unity as it asked me to update. Email me man, help would be greatly apritiated.
9:39 am on December 21st, 2011
Hey, can you rewrite the code so it works with Android? I tried it myself but i got lost completely.
4:00 pm on January 15th, 2012
Can you please help me. I am using Sketchup and don’t know how to export the model to Unity!!!
5:38 pm on February 5th, 2012
i keep getting this message: the variable FrontLEftWheel of ‘PlayerCar_Script has not been assigned
8:11 am on February 10th, 2012
hi, that is very nice thank you a lot and i had a question from your self :
if i want to build a race car game i don’t know what write for the other cars script for example the cars that is move with computer and automatically find the way and race with us
8:14 am on February 10th, 2012
excuse me my friend i do not read your tutorial fully thank you
12:47 pm on February 12th, 2012
Hello. I am using your AI script for my game. But, can it not work with more than 50 waypoints? Anything over around 50 works for a short time, but when the vehicle gets to waypoint 13(of 114 points), or another vehicle gets to waypoint 6(of 84 points), they stop and turn around, then continue along the path again.. any ideas?
7:49 pm on February 16th, 2012
Thanks so much for this tutorial.
for any others who might have symptoms of floaty cars or or cars not moving or way too much torque; check your scale! i was amazed to find out that i had created a car over two kilometres long thanks to an inadvertent export setting mistake
1:32 pm on March 13th, 2012
Hi. When I scale the car to make it bigger (2,2,2), it causes the car to flip all the time. Any idea on what I should do to counteract this?
2:35 am on March 16th, 2012
hey Andrew, its very good tutorial. My car is moving great but facing some problems.
1. Car’s body falls on ground but wheels r high in d air (but its moving).
2.Car falls in d space if used on terrain.
3. Car is turning right with moving forward.
5:02 pm on March 21st, 2012
I’m having problem with the AI system. The problem is that the car goes straight or barely turns. Do you know what is wrong.
10:50 am on April 6th, 2012
Thanks a lot . really good tutorial!
you helped me alot
7:58 am on May 14th, 2012
This tutorial is brilliant! its very close to something iv been looking for and its helped me a lot! thanks a lot
3:06 pm on May 20th, 2012
Unexpected token: var
expecting EOF, found ‘potentialWaypoints’
var potentialWaypoints : Array = waypointContainer.GetComponentsInChildren( Transform );
unexpected char
inputTorque = RelativeWaypointPosition.z / RelativeWaypointPosition.magnitude – Mathf.Abs( inputSteer );
3:38 am on May 21st, 2012
I must say brilliant tutorial. Being a beginner of Unity3D I found it very helpful.
I had a query though. Why don’t we use joins (hinge, spring,character etc) to join the wheels with the cars?? what are the drawbacks if we do that??
5:06 am on May 21st, 2012
Hey Andrew ,superb tutorial ,how can I change the control of the car to Twin Joysticks for Android ,I cannot find any answers that work to this anywhere
10:38 am on May 30th, 2012
Hi,
Excellent tutorial, many thanks. I have a question though – you don’t mention (that I can see) where the various scripts come from. For player control you mention ‘Car_Script’ – where does that come from?
10:44 am on May 30th, 2012
Sorry, ignore me I just found the link
7:58 pm on June 9th, 2012
Great job!!! but when i applyed the “Ai car” and “player car” scripts the car will not crashed and it can’t be controlled well so i need help……..thnx
11:55 am on June 18th, 2012
Great tutorial! The only problem I’m having is that when I switch the platform to android, I get the following complication error for the AI script:
Assets/Scripts/Car Control/AICar_Script.js(131,124): BCE0019: ‘position’ is not a member of ‘Object’.
Assets/Scripts/Car Control/AICar_Script.js(133,124): BCE0019: ‘position’ is not a member of ‘Object’.
Which is referring to:
waypoints[currentWaypoint].position.x,
waypoints[currentWaypoint].position.z,
Any help?
1:57 pm on July 26th, 2012
i have followed your tutorial but when i put the wheel align the wheel just hang in the air without moving can you help me please
the link have the scene and scripts
http://www.mediafire.com/?jnqh27cc8d9buqg
12:52 am on August 4th, 2012
hello.! a question.? when ia put in my game to jump start cars, or not working ..! any idea why this can happen.?
12:29 pm on August 8th, 2012
0000FF: The way I’d handle gear changes into too high a gear is to check that speed, on gear change is high enough. To mimic real cars with downshifting, track engine RPG separately from wheel RPM, and give each gear a range of effective accelerating and effective decelerating. e.g., while (ERPM < gearMin) accel = accel * 0.3
6:56 am on August 9th, 2012
Awesome work Andrew…. Very simple and clean code… helped me a lot.. Cheers…
3:17 pm on August 28th, 2012
Thanks You My Friend , it’s work so very fine
1:32 pm on September 8th, 2012
Hey Andrew, I tried using your scripts to control my own car model, the wheel alignment script works perfectly, but the player car script doesn’t seem to be working. The car doesn’t move at all. Know what I might need to tweak?
1:33 pm on September 8th, 2012
Ow, by the way, this is the best Unity tutorial ever.
3:47 pm on September 24th, 2012
Did anyone notice that changing the mass has nearly no effect on driving? why is that?
2:49 pm on September 30th, 2012
Hi,
this works for me perfectly on PC mode, but when I swich to Android this error appears:
AICar_Script.js(131,124): BCE0019: ‘position’ is not a member of ‘Object’.
Please help. I´m only a graphic designer and don’t have much experiences with coding.
2:02 pm on October 23rd, 2012
i was wondering about reverse, the code works perfectly , but when i slow it down and it goes into reverse it goes to fast , im i being stupid here , or am i missing something , that iit needs extra code for it
9:44 pm on December 8th, 2012
Thanks for the tutorial, really appreciated.
10:43 am on December 21st, 2012
Hey there ,agreed amazing tutorial ,this may be a stupid question but im trying to get the waypoint system + AI car into the Unity Car Tutorial scene ,but I cannot seem to get the car into it as a prefab ?and make it work ,the waypoint system would do on its own ,any ideas please guys ?
1:02 pm on December 21st, 2012
Did it
perfecto thanks Andrew you are the LEGEND
Best waypoint system I have EVER seen
even the paid ones
you are a programming LEGEND !
11:49 am on December 22nd, 2012
Amazing AI ,could anyone tell me why it does not compile for android ?
I get this error
Assets/Scripts/Car Control/AICar_Script.js(98,36): BCE0019: ‘position’ is not a member of ‘Object’.
Andrew if you know what is wrong here you would make my christmas a very happy one
10:58 am on December 23rd, 2012
Im asking for advice because other coders have said that the AICar_Script.js is actually a C# script ??? so I am totally lost now
10:21 am on December 24th, 2012
all fixed Merry Christmas guys ,and Andrew thank you for the best AI car system EVER
8:48 am on December 28th, 2012
btw did anyone work out how to stop the cars reversing all the time ?
9:41 pm on December 29th, 2012
could it be as simple as if the car IS reversing turn the steering for two seconds so its facing the right way again ? If only that was simple to code lol ,im a complete noob at this hehe …
4:08 pm on December 30th, 2012
var minSpeed : float = waypoints[currentWaypoint].GetComponent(”Waypoint”).minSpeed;
var maxSpeed : float = waypoints[currentWaypoint].GetComponent(”Waypoint”).maxSpeed;
var distanceToWaypoint = Vector3.Distance (Vector3 (waypoints[currentWaypoint].transform.position.x, transform.position.y, waypoints[currentWaypoint].transform.position.z), transform.position);
var finalSpeed = distanceToWaypoint;
finalSpeed = Mathf.Max (minSpeed, finalSpeed);
finalSpeed = Mathf.Min (maxSpeed, finalSpeed);
inputTorque = Mathf.Clamp (finalSpeed – speed, -1, 1);
Someone says to put these lines in the aicar script but they are not pragma strict and to be honest where woudl they go ? please ,I just want my cars to drive forwards on my Tablet lol
8:47 am on December 31st, 2012
When i put this (anywhere) in AIcarscript i get unknown ’speed’ thing ? Anyone or is this been long forgotten ?
I dont want to spend $100 bucks on a racing prefab because of one tiny error lol,and I still love this AI system so please ?
1:15 pm on December 31st, 2012
Screw it 100 bucks will be worth it to stop the headaches lol
happy new year guys
7:08 pm on January 13th, 2013
AWESOME TUTORIAL EVER!!! I LOVE IT!!
3:19 pm on January 14th, 2013
great tutorial.
thanks