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.
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%.