- Home /
Adding force to an object based on its current angle. (2D)
So to be simple, I need my object to move depending on its angle, Lets take a rocket for example, it has a thruster, adding an upward force, but as that rocket tilts, the direction of force changes itself, and that is what I need.
I've spent a while trying to figure this out, and maybe my mind is just passing the simplest of solutions, but here is what I came up with so far.
public float speed; //amount of force
public float rotate; //rate of rotation
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
rigidbody2D.MoveRotation (rigidbody2D.rotation - moveHorizontal * rotate
* Time.deltaTime);
float z = transform.eulerAngles.z + 90;
Vector2 angle = new Vector2(Mathf.Pow (Mathf.Cos(z), 2) ,
Mathf.Pow (Mathf.Sin(z), 2));
rigidbody2D.AddForce (angle * speed * 1);
}
}
What I've tried so far is to get a ratio, and use that to move, but the object just spazzed out
Answer by Limesta · Jan 02, 2015 at 06:22 AM
I FIXED IT WOO!
So I had figured out I had been doing everything wrong!
My issue here was simply that I was over thinking it. I went through some documentation and landed on this : http://docs.unity3d.com/Manual/DirectionDistanceFromOneObjectToAnother.html
Basically it tells you how to get a direction
I had went through and fixed up any code and cleaned it up, so what I did was I created an empty game object parented under my player, and as my player rotated, it did too, so now I have my code working! And best yet, I will share it to you all!
public float speed;
public float rotate;
public GameObject ForceDir;
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
rigidbody2D.MoveRotation (rigidbody2D.rotation - moveHorizontal * rotate * Time.deltaTime);
//Next 3 lines from http://docs.unity3d.com/Manual/DirectionDistanceFromOneObjectToAnother.html
var heading = ForceDir.transform.position - transform.position;
var distance = heading.magnitude;
var direction = heading / distance;
rigidbody2D.AddForce (direction * speed * -moveVertical);
}
Notes, the -movevertical is because I placed the forcedir object on the back of my player, so it didn't work out too well, by reversing input it fixed it.