Hi!

I am trying to get mye raycast to change its direction.

          Vector 3 direction = transform.forward;
				direction.x += (Random.value - 0.5f) * spread;
				direction.y += (Random.value - 0.5f) * spread;
				direction.z += (Random.value - 0.5f) * spread;

The problem is that when the transform is looking at an axis, it adds the spread to 0 (if its pointing at the Y axis, Y is zero so it will do 0 += (Random.value - 0.5f) * spread;), so it will raycast in a straight line, instead of all directions.

Does anyone know how I can fix this?

EDIT

bulletDirection = barrelEnd.forward;
				bulletDirection.x += (Random.value - 0.5f) * shotSpread;
				bulletDirection.y += (Random.value - 0.5f) * shotSpread;
				bulletDirection.z += 0f;
				
				shotSpread += spreadAmt;

Is the code for the bulletDirection and this is how I cast the ray:

Physics.Raycast (Camera.main.transform.position, bulletDirection, out info, Mathf.Infinity, shootmask)

What happens:

[13556-straight++down.png|13556]

Looking downwards (staright at an axis)

[13557-at+an+angle.png|13557]

Looking at an angle

What I am trying to make happen:

For the bulletDirection to change so that I can get bullet spread like a real gun (like in image 2), just independant from looking at an axis or not.

To sum up your idea, the “perfect” shot flies along the blue “forward” line coming out of the barrel. To get some spread, move the tip of that line a little bit left/right and up/down. That method does work, and is nice since it’s very easy to visualize.

The trick is moving the barrel’s left/right (the formal term is Local Coords.) Changing x will move left/right only if you’re facing north. If you’re facing East, then changing x just moves it closer/further.

The standard Unity way to move left/right is transform.right (which is your red/x arrow.) Very common, handy trick for lots of things. Using it looks like:

bulletDir = barrelEnd.forward; // note that this is length 1
bulletDir += spread * (Random.value-0.5f) * barrelEnd.right;
bulletDir += spread * (Random.value-0.5f) * barrelEnd.up;

Note how you don’t use dot-x. It’s like you’re saying “add part of my red arrow to my blue, and just work out the proper x/y/z for yourself.”

Now, moving forwards 1 and left by 0.3 is longer than a straight-ahead shot. If you were just setting speed, that would be a problem (badly aimed bullets would go too fast.) But ray casting doesn’t care how long the direction is, so it’s fine.

If you are looking to make a spread like for a shotgun, here is one link:

http://answers.unity3d.com/questions/492916/shotgun-bullet-spread.html

Looks like gimble-lock to me. Quaternions would probably help you here, do your offset with them or axis/angle functions. Or, detect that you are looking along Y (up or down) and special-case that to use alternate code.