Making a shotgun

I want to make a shotgun using raycasts. I have a script for a pistol and was wondering if I could edit it.

function Update () 
	pistolflash = GameObject.FindWithTag("pistolflash");
	// raycast settings
	var direction = transform.TransformDirection(Vector3.forward);
	var hit : RaycastHit;
	var localOffset = transform.position;
		// check to see if user has clicked
			// if so, did we hit anything?
			if (Physics.Raycast (localOffset, direction, hit, 400)) 
				// just so we can see the raycast
				Debug.DrawLine (localOffset, hit.point, Color.cyan);
				// print to console to see if we have fired
				print("we have fired!");
				// send damage report to object
				hit.collider.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
			Instantiate (muzzleflash, pistolflash.transform.position, transform.rotation);


Only difference between a gun and a shotgun, scripting wise, is that a shotgun casts more rays.

So if you want some spread to the rays from your shotgun you might be able to use something like this:

I havnt tested this script, nor do i know if it works, but it looks like something you could use :slight_smile:

just add a random.range in the angle, and cast like, 9 rays or so.

Hi man,

First up you need to create a for loop to do multiple rays.

The simplest way to get a shotgun affect would be to add a random XY each the origin offset vector, but you may want to think about altering the ray direction by very small degrees instead. I’ll provide the offset version for you as I don’t have access to unity to test out the tricker rotation stuff:

var shotgunPellets : int = 7; //How many pellets are in each shot

for (var i = 0; i < shotgunPellets; i++){ //For each pellet create a random origin and fire

    var randomX : float = Random.Range(-1.0,1.0);
    var randomY : float = Random.Range(-1.0,1.0);
    localOffset.y += randomY;
    localOffset.X += randomX;

if (Physics.Raycast (localOffset, direction, hit, 400)) {
//Hit code


//Audio and muzzle flash code

I would appreciate a version of this that would produce a cone shaped delivery of raycasts rather than tube as it were. I am struggling to find a way to randomize a ray’s direction within a cone of influence from an initial ray fired from my gun. I’ve been trying to wrap my head around this for quite some time!