- Home /
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
Answer by Statement · Dec 15, 2010 at 02:55 AM
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.
Answer by Wotan · Sep 17, 2010 at 10:59 AM
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.
I am still not able to achieve it.Where do i apply the force?To the bullet or the empty game object at the tip of the cannon or the cannon.No matter what I do ,the bullet keeps on going straight even if I rotate the cannon along with the empty object which is its child.
You attach a rigidbody to your bullet and make sure that "Is $$anonymous$$inematic" is not checked. When you want to fire apply a force to the bullet (Rigidbody.AddForce) in forward direction as explained by VoxelBoy.
Answer by VoxelBoy · Sep 17, 2010 at 08:51 PM
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.