Bullet spread using raycasting?

I’m trying to implement bullet spread to my guns, but so far with no luck at all.

My bullet.js code looks like this:

function Awake()
{
	var ray = Camera.main.ScreenPointToRay(Vector3(Screen.width / 2, Screen.height / 2, Camera.main.nearClipPlane));
	var hit : RaycastHit;
	
	if(Physics.Raycast(ray, hit, maxDist))
	{
		if(decalHitWall && hit.transform.tag == "Level Parts")
		{
			var hitRotation = Quaternion.FromToRotation(Vector3.forward, hit.normal);
			Instantiate(decalHitWall, hit.point + (hit.normal * floatInFront), hitRotation);
		}
	}
}

I want to modify this code so that it fires the bullets to the center of the screen (camera) and add a little bit of bullet spread (the bullet spread should be controlled from the inspector since it will be different for each bullet / weapons)…

Can anyone help me? :slight_smile:

The easiest solution to this problem is to vary the screen pixel used for creating the Ray:

  var pos = Vector3(Screen.width / 2, Screen.height / 2, Camera.main.nearClipPlane);
  pos += Random.insideUnityCircle * spreadFactor;
  var ray = Camera.main.ScreenPointToRay(pos);

‘spreadFactor’ can be set on a per-weapon basis. Note with this code, the physical spread at the hit point will vary more as the distance grows…like a real weapon.