How to shoot a rocket in the direction object is facing

I just started playing around with 2D in Unity and I created a simple rocket that rotates in 360 degrees on the Z axis. I have made missle objects and have it setup so that that when they spawn they are pointing in the direction of the rocket. That part of things is all good. What I am not sure of is how to add force to the missle so that it shoots off in the direction it is facing. I have the AddForce code which takes a Vector2, but I really don’t know what sort of equation to put in the function so that the force ratio changes depending on the rotation. I suspect that there is some sort of mathematical formula needed for this.

For example if the rocket is pointing straight then I would want only force applied along the x axis and absolutely nothing in the y. If I were pointing straight up I would want the opposite with only a y axis force added.

I am sure this has been done before as it is a pretty common game mechanic. I just wanted to use a lifeline and ask the audience before I go about trying to come up with a mathematical formula on my own.

Thanks again everyone for your help. You guys rock. Excellent support community which really helps us noobs.

You should be able to use the built in Vector2 for your direction. Vector2.Up, etc. But those really depend on how you setup your prefab, and the object which Instantiates it. If you work in 2D, and your planes are all correct. +y is up, +x is right, etc. And your bullet prefab was created horizontal with the x axis, and faces the positive x direction. You should be able to use Vector2.right to shoot it ‘forward’.

Try this:

	var BulletSpeed : float = 1000;
    var fwd : Vector3;
        var fwdxy : Vector2;

	function Start () 
       fwd = transform.TransformDirection(Vector3.forward);
       fwdxy = (fwd.x,fwd.y);
       rigidbody2D.AddForce(fwdxy * BulletSpeed, ForceMode.Impulse); 

You should get the direction your object is heading, and use that as the initial force vector.

Have you checked Vector2.Angle, or Quaternion.FromToRotation?

Anyway exactly how to do it will depend on your curent code. Post some showing how you handle your gameObject if you want a better answer.

There are many way to do this. The easiest way is this.

missle.rigidbody.AddForce(rocket.transform.forward * _force);