Weapon Spread?

Hey all i was looking at some threads trying to figure out how to do weapon spread (as you fire your weapon gets less accurate) but i can’t quite understand how it works.

This is what i was going off of…
http://forum.unity3d.com/threads/56423-(Script)-Weapon-Control-Script-v1_1-Aug-8-2010?highlight=weapon+spread

the only code i saw for spread was…

var Spread : float = 0.1;   // How much variation there will be in the spread of each shot (Small numbers are better)

In the scripts provided i saw no where that he called that variable to increase the spread…

If anyone is able to help on this or provide me with an example of how to make it work in another way, it would be greatly appreciated

Do a minSpread and a maxSpread with spreadTimeLimit. This way, in your script, you can say spread=Mathf.Lerp(minSpread, maxSpread, (Time.time - timeShootPressed) / spreadTimeLimit;)

You would then, just have to make timeShootPressed Time.time in Input.GetButtonDown(“Fire1”)

ok that’s something like i figured it would be (i actually was coding this in UDK and then we decided to move to unity cuz UDK sucks and unity rocks)

So i’m assuming spread is like a set thing already in the engine, like it knows what spread does?

Its the actual mechanics of the spread that hes confused on though, i think.

Naw, He’s using it. In that package you linked, the spread is happening in the script attached to the bullet, in Start(). All he’s doing is applying a small random rotation on the x and y axes to the bullet after it is instantiated:

transform.Rotate(new Vector3(Random.Range(-Spread,Spread),Random.Range(-Spread,Spread),0) );

oh ok, thanks, i think i saw that but didn’t understand what he was doing lol

why is it (-Spread,Spread)? couldn’t it be Spread… little confused on how that calculation is working

Random.Range(x,y) returns a random value between x and y, so its applying a Random rotation between -0.1 and 0.1 to the x and y axes of the rotation of the bullet. If you just put spread in there, it would ALWAYS have the same rotation (0.1) for those axes, so it wouldn’t spread, it would just have the same offset every shot. Finally, it needs to have a range that goes into the negatives or else the spread would only “spread” to one side.

here. I use this:

//thisreturns a random direction. 1 is any direction, 0 is perfectly straight. 0.25 would be 45* cone
//trans should be a transform that is effectively the gun barrel.  You can change this to just be a vector3 if you want, and just pass the
//direction that is what the gun would shoot if it was perfectly accurate
static function SprayDir(inaccuracy : float, trans : Transform) : Vector3{
	return Vector3.Slerp (trans.TransformDirection(Vector3.forward), Random.onUnitSphere, inaccuracy);
}