How best to create a shotgun shot?

I’m having a bit of difficulty with this, I’d like to create a collection of bullets at the firing position and send them in random angles using addforce - any idea how i might do this?

Cheers all!

I would set a pellet count variable and do a for loop that spawns as many pellets as pelletCount, adding a random offset to the instantiate rotation. I use something like:

var pelletPrefab : Rigidbody;
var pelletSpeed : float = 150;
var pelletCount : int = 5;
var spreadFactor : float = 0.01;
var fireRate : float = 0.5;

private var nextFire : float = 0.0;

function Update () {

	if(Input.GetButtonDown("Fire1")  Time.time > nextFire){
		var pellet : Rigidbody;
		for(var i = 0; i<pelletCount; i++){
			var pelletRot = transform.rotation;
			pelletRot.x = Random.Range(-spreadFactor, spreadFactor);
			pelletRot.y = Random.Range(-spreadFactor, spreadFactor);
			pellet = Instantiate(pelletPrefab, transform.position, pelletRot);
			pellet.velocity = transform.forward*pelletSpeed;
		}
		nextFire = Time.time + fireRate;
	}
	
}

Thanks, I’ll try this out now!

This works, but the shotgun pellets are rigidbodies and so they end up just clustering together and moving slightly back and forth when instantiated. What am I doing wrong?

Oh, you mean because they are interacting with each other? I would put projectiles on their own layer and set it up in the layer-based collision matrix so they ignore each other.

Thanks, that’s a good idea, cheers!

The layers worked perfectly, cheers, but oddly I’m getting different rotations for each pellet, but they’re all still travelling in the same direction.

That’s my code, I can’t see why it isn’t working…!

You should use the transform of the pellet and not the transform of the calling script:

pellet.rigidbody.AddForce(**pellet.**transform.forward * shootForce);

That does indeed work, but for some reason they’re all travelling along world axis lines instead of being rotated along the player’s axis (therefore meaning you can shoot yourself in the face if you’re facing the wrong direction). Its odd because none of my other bullets do this, and they’re literally shot in the same way…

Oops, silly me, I’m a fool. Turns out “pelletRot.x = Random.Range(-spreadFactor, spreadFactor);” should have been “pelletRot.x = pelletRot.x + Random.Range(-spreadFactor, spreadFactor);” and the same for Y…I hope my ignorance helps people in the future!

Ahh my bad, I wrote that off the cuff at work… I meant to put += on those lines there :slight_smile:

No worries, its good practice for me! :slight_smile: