Shooting a bullet/ projectile PROPERLY

I'm working on a FPS game, and have only a little knowledge about scripting and animations. I encountered a problem, spent all day long searching answers for it, still no hope. I attached this script :

var projectile : Rigidbody;
var speed = 20;

function Update () {
    // Put this in your update function
    if (Input.GetButtonDown("Fire1")) {

    // Instantiate the projectile at the position and rotation of this transform
    var clone : Rigidbody;
    clone = Instantiate(projectile, transform.position, transform.rotation);

    // Give the cloned object an initial velocity along the current
    // object's Z axis
    clone.velocity = transform.TransformDirection (Vector3.forward * speed);
    }
}

into my camera, but when i press shoot, it shoots the bullet all around. Even if im aming at the same spot, sometimes it shoots upward, sometimes it shoots downwards, sometimes from the centre, sometimes from below, even from on top. How do i fix this problem?

Also, can anyone give me a scrip suitable for a gun that shoots using raycast? REALLY needed help, thanks.

From the Unity Rigidbody.velocity documentation:

In most cases you should not modify the velocity directly, as this can result in unrealistic behaviour.

Instead of setting the object velocity, add force to the object:

clone.AddForce(clone.transform.forward * speed);

I've not tried instantiating a Rigidbody before, only a Transform/GameObject prefab, but I can't think of a reason it wouldn't work. Try pasting this code over yours.

var projectile : Transform;
var bulletSpeed : float = 20;

function Update () {
    // Put this in your update function
    if (Input.GetButtonDown("Fire1")) {

    // Instantiate the projectile at the position and rotation of this transform
    var clone : Transform;
    clone = Instantiate(projectile, transform.position, transform.rotation);

    // Add force to the cloned object in the object's forward direction
    clone.rigidbody.AddForce(clone.transform.forward * shootForce);
    }
}

Is it possible that you have a collider on your camera that is colliding with your projectile? Use `Physics.IgnoreCollision(clone.collider, collider)` to ignore collisions between the fired object and the object doing the firing.

Edit: moved from comment to answer

Your Bullet will always fire at what it is attached to, so if you attach the bullet with the firing script, and a small invisible square without a mesh, then it should fire at, and through, the square

I changed this

clone.AddForce(clone.transform.forward * speed);

Into

clone.AddForce(clone.transform.forward * 1000);

And it worked :o

rigidbody.AddRelativeForce(Vector3.forward * Time.deltaTime * speed);

I hope that it works :wink:

Your issue is that your bullets are spawning ONTOP of other objects. And physics says this is not possible, causing them to fly out in random directions. Use Physics.IgnoreCollision(bullet.collider,playerobject.collider) or replace playerobject with any collider that is in the same spot the bullet is spawning.

This script is not mine, but i edited it A Lot!
This is what i use. I hope it helps you and many others, it is Very good!

//Added Comments To Help You Guys:
//Attach to empty object, in front of barrel

var projectile : Rigidbody; //The Bullet

var speed = 250; //Speed Of The Bullets

var fireRate = .5;//Time Delay Between Shots!

var flash : Rigidbody; //The Muzzle Flash

function Update()

{

        InvokeRepeating("Fire",fireRate,0.3); //Shoot Delay

}

 

function Fire()

{

    if( Input.GetButtonDown( "Fire1" ) ) {
	audio.Play();
        
 var instantiatedProjectile : Rigidbody = Instantiate(projectile, transform.position, transform.rotation );
 var instantiatedFlash : Rigidbody = Instantiate(flash, transform.position, transform.rotation );
 Destroy(GameObject.Find("GunFlash(Clone)"));

        instantiatedProjectile.velocity =

transform.TransformDirection( Vector3( 0, 0, speed ) );

        instantiatedFlash.velocity =

transform.TransformDirection( Vector3( 0, 0, 0 ) );
        

        Physics.IgnoreCollision( instantiatedProjectile. collider,

transform.root.collider );

        CancelInvoke();

    }

}

I know this post is 3 years old but this is mainly for Anyone who needs help, Enjoy

Hi to all,

If you have attached a rigidbody at your bullet gameobject you may apply a script like the following:

bullet.transform.rotation = spawnPoint.rotation;
bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * bulletSpeed;

This works fine for my FPS player which can fire to any direction. The “spawnPoint” is a game object attached at the end of the gun transform but you can use any other transform you want.

A more complete and comprihensive answer would be:

Please insure your bullet prefab has a rigidbody attached and that the collider is a trigger

Why a trigger?..You do not want, need or have to simulate the collision…It’s a game…and if you’re asking this q Then you are in the wrong place and time in your programming track to be asking the q, if you’re planning on simulating ultra realistic physics using a game engine. Leave that to the people creating directX physics/ librarys / stuff / w/e {Obviously im not a pro, but logic is logic x.x }.

using UnityEngine;
using System.Collections;

public class GunFire : MonoBehaviour {

	public GameObject bullet; //the bullet prefab
	public GameObject barrelRef; //Where we are shooting the bullet from **This is extra Nit Picking From Me. Its a empty object just ahead of the barrel**
	public float bulletSpeed = 480.0f; //the speed in meters per second we want if rigidbody mass is 1. 
	//This value should be multiplied by the amount of fixed update frames/second in your game. so if 0.02 then 1/0.02 = 50 - see Lines 17 and 18
	//20 for bullet speed translates to 20/50 = 0.4 m/s BTW if your rigidbody mass is 1
	void Update () { //<-----We are generating one instance in one frame. no need for fixed update.
		if (Input.GetButtonDown("Fire1")) {
			
			// Instantiate the bullet at barrel ref
			GameObject bclone = Instantiate(bullet, barrelRef.transform.position, barrelRef.transform.rotation) as GameObject;
			
			// Add force to the bullet in the forward direction * ( bullet speed * (1 / Time.fixedDeltaTime) ) this must be done if your input bulletspeed units is in m/s or ft/s
			bclone.rigidbody.AddForce(bclone.transform.forward * (bulletSpeed * (1/Time.fixedDeltaTime)) );

		}
	}
}

Enjoy.

PS. Random Ranting :?

//And if you’re using imperial "fps or ft/s" I’m assuming your assuming that Unity units = imperial units...stop being an idiot the exact same fixedDeltaTime math applies
//if not and your using fps with Unity units assumed to be meters*1 then simply convert fps to ms. The math: fps * 0.3048 = ms. so 1200fps = 365.76ms.
//*1 Im hoping your seriousely not combining the two units of messure in your game. Save yourself some headach and pick one.
//please remember that the mass of the rigidbody is subjective. Unless your going for oeber computing and ultra realistic physis {please don't do this with a game engine}
//leave it at 1. Or else you will have to multiply bulletspeed with it's mass. So if you make the rigidbodys mass 0.0075 kg {9x19mm Bullet} you will get 480ms * 0.0075 kg = 3.6 newtons per second force
//3.6 is in newtons per second. so your code will look like this
//clone.rigidbody.AddForce(clone.transform.forward * ( (bulletSpeed * clone.rigidbody.mass) * (1/Time.fixedDeltaTime)) ); <------- Do not do this.
//the force exurted is not worth simulating in a game engine using physics. use scripting instead and use bclone.rigidbody.AddForce(bclone.transform.forward * (bulletSpeed * (1/Time.fixedDeltaTime)) );

Edit : Some more ranting at the top.