Weapon Spray issue

Hello,
I’m trying to add a slight weapon spray to my game. The way im doing it is by slightly adjusting the Y rotation to give me a horizontal type spray but I’m having some really bad issues with it.

At the moment it is shooting off to an angle and if I rotate the player around 360 the offset gets increased and the weapon no longer fires forward but off to the side, this increase the more I rotate the player in the same direction.

Any help would be great! thanks.

Code:

private void CalculateSprayWeight()
	{
		Quaternion direction = firePoint.localRotation;
		direction.y += Random.Range(-sprayWeight, sprayWeight);
		firePoint.Rotate(direction.x, direction.y, direction.z);
	}

Hi @alexlem_17

Your code doesn’t make much sense, I’d rather go this route:

  1. Create a forward facing vector in world space.
  2. Add offset to it’s x and y position. Now you have a 1m “stick” (direction vector) that faces forward in world space with slight offset.
  3. Now rotate this direction vector to your object’s rotation space. This can be done using transform.TransformVector.

This way your world space vector is now aligned to your player’s transform’s forward direction, but with the same offset that it had in world space.