2d cannon bullet

I just started scripting with C#.Basically I have a cylinder as a cannon and at the tip I have attached an empty object from which the bullet emerges(Its a 2D game).When i press fire I want the bullet to travel in the direction my cannon is pointed.How do I do this.I only know a script to fire straight up.Thanks

Make the bullet a rigid body so that the physics engine takes care of its movement. When you fire it, add a force in the direction of your cylinder. That's it.

Use the transform.forward property of the empty game object you have that's at the tip of the cannon. That will give you the 3D world-space direction that you need to use as the direction of the velocity of the bullet. The forward axis is the same as the blue axis you see when you select an object in the Hierarchy. Similarly, transform.right is the red axis, and transform.up is the green axis.

Welcome to the wonderful land of C#!

Your cannon should have your empty game object (let's call it "spawn") be a child and have its blue axis (forward, z axis) pointing away from the cannon to the direction you want it to travel. This will help us instantiate objects facing the direction your cannon is pointing.

To create the cannon ball you just need to instantiate a cannon ball prefab at the spawn point.

public class Cannon : MonoBehaviour
{
    public GameObject cannonballPrefab;

    void Update ( )
    {
        if ( Input.GetKeyDown( KeyCode.Space ) )
        {
            FireCannon( );
        }
    }

    void FireCannon ( )
    {
        Transform spawn = transform.Find( "spawn" );
        GameObject cannonball = Instantiate( cannonballPrefab, 
                                             spawn.position, 
                                             spawn.rotation ) as GameObject;
    }
}

The actual cannonball prefab should have a Rigidbody and a ConstantForce script attached to it so it flies off in an arc. If you dont want to use physics you can create a simple straight moving script such as:

public class MoveForward : MonoBehaviour
{
    public float speed = 1.0f;

    void Update ( )
    {
        transform.Translate( Vector3.forward * speed, Space.Self );
    }
}

If you chose to use this on your cannonball prefab, you must not use Rigidbody or ConstantForce. This will cause your ball to travel forward at a fixed speed that is configurable in the inspector.