Creating a movable car
Theory:
Programming realistic car movement is much harder and advanced than anticipated. Controls I usually use to move an asset is based around transforming the assets position along an axis when a key is being pressed. This logic does not suit car movement because a car does not behave that way.
Cars move with increasing velocity depending on the amount of torque being generated from the driver by pressing the pedals. When a driver hits the breaks the car doesn't go to a dead stop immediately it does so over a short period of time due to car velocity and tire friction.
These factors all need to be considered in order to create a car game which simulates realistic movement as much as possible. I did not feel I could create a script from scratch given my minimal coding experience in Unity3D so I used a tutorial to help out.
Setting the stage:
Before creating and applying a script to the car asset, car mesh talked about in creating assets section, I needed to set up the car properly. When importing a model which includes greater than one mesh item, Unity3D automatically adds all the meshes as a child of an empty game object. I do not want this.
First I needed to un-child all the mesh items, make the car chassis the main parent and then delete the empty game object. I then need to rename all my objects, for future reference, to appropriate names such as FrontRightWheel, RearLeftWheel, Chassis etc.
Now I needed to create an empty game object which will act as a container for the wheels. I dragged the four wheel into this container making it the parent and then attached it to the car.
I then needed to duplicate the container, renamed each wheel, add a wheel collider and then remove the mesh as we don't need it. The wheel colliders will be used to ray-cast down at the ground which allows for constant collision detection with the floor.
I now need to add a rigidbody to the car chassis which simply adds gravity to the car and then two box colliders around the car mesh used to bottom and top collisions.
Creating the script:
Using the car tutorial from the Unity3D assets store, http://u3d.as/content/unity-technologies/car-tutorial/1qU, I was able to develop a script in the C# language. The script was developed using the front two tires to steer the car using torque.
The script translates the players position using the axes and the stored input keys "Vertical" and "Horizontal" which has the stored keys values in them.
The script also uses a set list of integers which is used to increase the amount of tire rotations depending on the speed the car is travelling at.
I also used a javaScript code which would handle tire movement which basically rotates the tires.
No comments:
Post a Comment