- Home /
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(Input.GetButtonDown("Fire1"))
{
// 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);
}
AudioSource.PlayClipAtPoint(gunshot,transform.position);
Instantiate (muzzleflash, pistolflash.transform.position, transform.rotation);
}
}
Answer by demize2010 · May 27, 2011 at 09:43 AM
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
Answer by Kacer · May 27, 2011 at 09:39 AM
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: Clicky
I havnt tested this script, nor do i know if it works, but it looks like something you could use :)
just add a random.range in the angle, and cast like, 9 rays or so.
Answer by RowleyBirkin · Mar 18, 2013 at 03:22 AM
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!
@rowleybirkin, this question is 2 years old, and what you are looking for is different anyway. So why don't you post this as a new question?
Your answer
![](https://koobas.hobune.stream/wayback/20220612090503im_/https://answers.unity.com/themes/thub/images/avi.jpg)