Spray Shot Script

I'm trying to make a bullet spray script but for some reason it only fires in a single direction, no matter how the character turns around. Any reason for this?

/// Add spread shot

    var rotation : Quaternion = Quaternion.identity;
    rotation.eulerAngles = Random.insideUnitSphere * 10;
    transform.rotation = rotation;
    var BulletShot = Instantiate(Bullet, transform.position, transform.rotation);
    BulletShot.rigidbody.AddForce(transform.forward * 1000);

Ok, if I get what your talking about... Then this should work:

 var gunRecoil : float;

 var BulletShot = Instantiate(Bullet, transform.position, transform.rotation);

 var randomX = Random.Range(-gunRecoil,gunRecoil);
 var randomY = Random.Range(-gunRecoil,gunRecoil);

 var dir = transform.TransformDirection(randomX,randomY,1000);
 BulletShot.rigidbody.AddForce(dir);

move the gunRecoil variable to the first line of the script.

Hope this helps!

Also, I would instead of setting force, set the velocity manually:

BulletShot.rigidbody.velocity = dir;

Also there might be some errors... I have not tried it in unity yet.

Hope this helps!

I guess this script is attached to your weapon?

By setting Transform.rotation the object will be rotated in world space. To rotate it relative to the parent use Transform.localRotation.

And second: you can assign eulerAngles but they don’t wrap around automatically. You will get an error/warning when you try to set them to values outside [0…360]. Use the built in function Quaternion.Euler instead.

var rotation : Quaternion = Quaternion.Euler(Random.insideUnitSphere * 10);
transform.localRotation = rotation;
var BulletShot = Instantiate(Bullet, transform.position, transform.rotation);
BulletShot.rigidbody.AddForce(transform.forward * 1000);

ps. I like your way to calculate the spreading ;)

The z rotation is not really useful but a bullet don’t have a top-side you have to keep up.

If this script is on your weapon, the weapon gets also rotated. if you don’t want the z rotation, just set the z value to 0.

var rotation : Quaternion = Quaternion.Euler(Random.insideUnitSphere * 10);
rotation.eulerAngles.z = 0;
transform.localRotation = rotation;
[...]

A similar question has been answered before. Try this.