This is part of an ongoing mission to explore making a simple controlled vehicle using the Unity Wheel Collider. See the introduction for a chapter list.
Putting some wheels on the truck
In this part of the mission I am going to step through setting up the truck model with wheel colliders. At the end of it we should be able to have the truck roll down a slope under the effects of gravity.
First a created a new project in Unity and then imported the truck and wheel assets given to me by Marc as 3ds objects. I asked for the wheels separately so I could make them into a prefab and repeat them around the truck. I can also eventually rotate the wheel meshes so they appear to be rolling across the ground.
After attaching the wheels I then attached an empty Game Object to the truck. To this object I added a wheel collider component.
The wheel collider is a component so it has to be added to a game object of some variety. I could have added it to my wheel mesh, but then I would not be able to rotate the wheel without rotating the collider.
As a component, the collider inherits the transform (position, rotation and scale) of the object it is attached to. By using an empty game object I am able to reposition align the collider without having to change any of the meshes.
Marc knows his stuff, so he created the truck and wheel meshes in the correct orientation. However if I had created the wheels using Unity’s in-built cylinder object they would have started in the wrong orientation – they would have been lying flat on the ground and I would have to rotate them 90 degrees to stand them up. If I then attached a wheel collider directly to them the collider would inherit their transform and be pointing 90 degrees in the wrong direction.
Trust me, just attach them to an empty game object.
Here is the final object hierarchy. Truckbod has six wheel meshes and four wheel colliders attached.
I only added four wheel colliders because that is the number a vehicle will typically have, and I want to be able to use any scripts I write in future projects. Four colliders on the furthest front and back wheels should be fine for our truck as long as we keep the terrain pretty flat.
Finally I added a plane to act as the ground, and a light and camera to test the scene. I have not added any forces to the objects here, so left to their own devices they do not do much – the truck just sits on the perfectly level plane.
For the simplest of tests I rotated the plane to give it a slight downward slope. Then when the scene is run the truck trundles off down the slope – and eventually drives off the end.
That’s the end of part one. Next up is adding a motor and steering.