- Home /
Making a gun shoot
I have this script it is supposed to make a gun shoot but the bullet does not go forward here it is:
var speed = 50; var fireRate = 0.11; private var lastShot = -10.0; function Update () { if(Input.GetButtonDown("Fire1")){ if(Time.time > fireRate+lastShot){ clone = Instantiate(projectile, transform.position, transform.rotation); projectile.tag = "Bullet"; clone.velocity = transform.TransformDirection( Vector3 (0, 0, speed)); lastShot = Time.time; } Destroy(clone.gameObject, 3); } }var projectile : Rigidbody;
Answer by DGArtistsInc · Mar 06, 2012 at 03:46 AM
if it is a rigidbody then i would not use velocity and transform direction. I would use rigidbody.AddForce instead for example
take out:
clone.velocity = transform.TransformDirection( Vector3 (0, 0, speed));
and put in:
clone.rigidbody.AddForce(Vector3.forward * speed);
Vector3.forward
will always return (0,0,1); we probably want to use something like transform.forward
here, to launch our bullet in the direction the shooter is currently facing.
What are you talking about? Its the Vector3 of the rigidbody so it has nothing to do with the direction the character is facing. It matters what direction the object doing the instantiating is facing. Commonly a gun model is the child of an empty GameObject and that empty GameObject has the script on it usually. And when an object is Instantiated it is facing the direction that that empty GameObject is facing. SO it will shoot in the direction of which the shooter is facing so long that the empty GameObject and the Shooter are facing the same Direction.
As described by Unity's documentation: AddForce() uses world coordinates, which implies that force in the direction (0,0,1) would push it along the world's z-axis. Perhaps you're thinking of AddRelativeForce()?
If this is code that's worked for you in the past, more power to you.
yes it does work for me... every time... when it says it implies force on the direction(0,0,1) it does not imply force in the WORLD'S Z Axis it implies force on the OBJECT'S Z axis Causing it to move forward. I see the point yo are making however AddForce has always worked for me. AddRelativeForce can be used as well though