- Home /
How to make 2d Vehicle/car physics in unity 3d 4.3 2d physics?
I want to make a 2d car phyics driving game in the new unity 4.3 engine. I have setup my car sprite and attached rigidbody 2d to it and also setup the wheels using circle collider and spring joints but the only problem i get is how do i move my car according to arrow keys. I have tried Rigidbody2d.AddForce but it only work on specific axis not in the direction where the car is facing. please help me from getting out of this trouble. also thanks in advance.
Answer by LostInCode404 · Dec 17, 2013 at 03:22 PM
I've got the answer. make some variables as shown.
var force : Vector2;
//vector for Rigidbody2d.Addforce
var car : Transform;
//the transform of the car
var power : int;
//to give magnitude of force
var trigfunction : Vector3;
//it will give the value of trigonometric functions for the current eulerangles (rotational position) of car
We will use here simple concepts of trigonometry (If you know a little of it, if not just see the way it works)
In function update use this code
function Update () {
trigfunction = car.TransformDirection(Vector3.right);
//now the x component of var trigfunction will give us the value of cos of eulerangle and y will give sin of eulerangle of car
force.Set(trigfunction.x,trigfunction.y);
//assign the x and y components to the force
//its a concept of vector physics, x = r cosA , y = r sin A
if (Input.GetKey(KeyCode.W))
rigidbody2D.AddForce(force*power);
//assign input key to add forward force
if (Input.GetKey(KeyCode.S))
rigidbody2D.AddForce(force*power*-1);
//assign input key to add backward force
}
if the position is horizontal, sin 0 = 0 and cos 0 = 1 the whole force will be in horizontal.
if the position is vertical. sin 90 = 1 and cos 90 = 0 the whole force will be in vertical.
if the position is anywhere else, the force will be in direction of car in accordance with the values of sin and cos of eulerangles.
It works 101%.
Thanks,3d Scientist it works 101% as you said. It is the best solution for this problem as it seems to me. I just attached this script to car and give the car transform and the car runs on my keys.keep it up.again thanks for the script
I've made a good 2D Car physics game from your idea and uploade it on my new blog (with source code link). You can download it and check it out www.physicist3d.blogspot.com
Nice work... But I still feel there is a lot to go before you can say its complete. I have found another article by The Game Contriver which is quite realistic than the ones I have come across so far. If anyone needs it, check the link below