spraying bullets

ive been working on an fps game in unity for some time now but i dont know how to spray my bullets instead of the bullets going straight forward which isnt very realistic.

can anyone help me with?

You'll need to use Random. I write code better than I write sentences:

public var maxDivergence : float = 5; // The amount in degrees the bullet can be "off" center

function Shoot() {

    // start with a perfect shot
    var divergence : Vector3 = Vector3.zero;

    // then we want to randomize the rotation around the X axis
    divergence.x = (1 - 2 * Random.value) * maxDivergence;
    // and the rotation around the Y axis
    divergence.y = (1 - 2 * Random.value) * maxDivergence;
    /* Random.value only gives you a positive float between 0 and 1
     * (1 - 2 * Random.value) makes that between -1 and 1
     */

    // instantiate the bullet
    var bullet : Transform = (Transform) Instantiate(bulletPrefab, transform.position, transform.rotation);

    // now we'll apply the divergence
    bullet.Rotate(divergence);

}

It would be more efficient to make the Quaternion rotation before instantiating the prefab but Quaternions scare me. I'm making this a Wiki maybe someone will add it in.


Also check out the answers on this question http://answers.unity3d.com/questions/5602/fps-gun-accuracy-bullet-tracers

@Rennat, Since I can’t add a reply for some reason, I will post it as a separate answer. I enjoy that there is a script that uses angles instead of vector movement. This way, the gun will be less accurate at distance. A simple vector movement means that while the gun will be inaccurate, it will be just as inaccurate at infinity distance than at point blank distance. Thanks!

Heres the script that I use for my weapons. It may not be efficient but it does get great results.

public float accuracy;
public float aimAccuracy;
public float hipAccuracy;
private Quaternion shotAcc;

public Transform shotPoint;

if(Input.GetKey(KeyCode.Mouse1))
        {
            accuracy = aimAccuracy;
            camObj.fieldOfView = 40;
           
        }
        else
        {
            camObj.fieldOfView = 50;
            accuracy = hipAccuracy;
        }

if (semiauto == true && !isReloading)
        {
             if (Input.GetKeyDown(KeyCode.Mouse0) && !Input.GetKey(KeyCode.LeftShift) && Time.time > nextFire)
                {
                    if (magAmmo > 0)
                    {

                        shotAcc = Quaternion.Euler(Random.Range(-accuracy, accuracy), Random.Range(-accuracy, accuracy), 0);
                        shotPoint.localRotation = shotAcc;


                        Shot();
                        shotSound.Play();
                        magAmmo--;
                        shotsFired++;
                        muzzleFlash.Play();
                    }
                }
            
        }