Gun Only Fires When Moving Sideways or Backwards

I am just beginning using Unity and I made a very simple gun (if you can call it that), which fires spheres. Here is my code for firing the gun:

var shootForce:float;
var bulletPrefab:Transform;
var bulletSpawner:Transform;

function Update () {
	if (Input.GetKeyDown(KeyCode.Mouse0)) {
		instanceBullet = Instantiate(bulletPrefab, bulletSpawner.position, Quaternion.identity);
		instanceBullet.rigidbody.AddForce(transform.forward * shootForce);
	}
}

Unfortunately the gun only correctly fires when moving sideways or backwards. Otherwise the bullets just fall to the ground. I have a feeling that this might have to do with the bullets colliding with one another, but I don’t know how to fix the problem. I have tried to move the bullet spawner around and change the shoot force, but neither worked.

2 Answers

2

If your spawner is a child object, solving this problem might be as easy as using the rotation of the spawner in the Instantiate:

instanceBullet = Instantiate(bulletPrefab, bulletSpawner.position, bulletSpawner.rotation);

Tried it, but it seems to be doing the exact same thing.

WHATEVER HAPPENED TO ANSWERING A QUESTION!? Stop commenting when yo have an answer, please

WHATEVER HAPPENED TO ANSWERING A QUESTION!? Stop commenting when yo have an answer, please

Tried your second suggestion. Still no change.

Was the Debug.Ray() pointing in the correct direction? Was OnCollisionEnter() reporting any hits and if so what was it hitting?

My guess is your shooting yourself. So if you’re moving forward, and you shoot, the bullet hits you instead of shoots ahead of you. Are you ignoring yourself in the hit calculation? Physics calculation? Is your spawner well enough in front of your player?

These are all good questions and suggests an answer. Had you worded it 'Check that you are ignoring....' it would be a good answer.

I can't answer without knowing more information, thus the questions. And the questions themselves result in pretty obvious solutions once you know the answers. Again, new to the forum, but a little courtesy goes a long way.

There is currently noting that is calculating a hit. My character is just a first person controller, so it does not have a rigid body for physics, and I already tried moving the spawner farther away from the person, but the problem persists.

It still sounds like this is the problem. Try using ignore collision between the projectile and the player and between the projectile and the spawner. http://docs.unity3d.com/Documentation/ScriptReference/Physics.IgnoreCollision.html

I ignored the collision, but it still is the same. Sorry.