Raycast going the wrong way

This is for testing a shotgun mechanic using raycasts. I followed a tutorial on YouTube, and it works. Only problem being it doesn’t go the right way.

The code responsible for handling the raycasting and spread:

            local x = math.random(-config.spreadhorizontal, config.spreadhorizontal)
			local y = math.random(-config.spreadvertical, config.spreadvertical)
			local origin = tool.Handle:WaitForChild("FirePos").WorldPosition
			local direction = (mouse.Hit.p - o) * CFrame.Angles(math.rad(x), math.rad(y), 0).LookVector
			local ray = workspace:Raycast(o, d.Unit * 1000, rp)
			local intersection = ray and ray.Position or origin + direction
			local distance = (origin - intersection).Magnitude

Don’t really know what’s going on. Help is appreciated.

1 Like

Two possible problems here:

  1. You define a variable called ‘direction’ but then raycast in the direction of ‘d.Unit’, not “direction.Unit”. What is d? Where is it set?

  2. The vector multiplication you’re doing with your (p-o) * LookVector is basically nonsense. This is doing element-wise multiplication of the two vectors, which is not the rotational offset you’re after.Probably the example had a typo or you miscopied it.

You can do what you want with a CFrame multiplication, one could argue that it’s a bit wasteful to construct a CFrame to rotate a vector, but nevertheless, it’s still probably faster than doing it the vector addition way in lua, so here you go:

local randDir = dir.Magnitude * (CFrame.new(Vector3.zero,dir)*CFrame.Angles(math.rad(x),math.rad(y),0)).LookVector

This makes a CFrame with a LookVector in the direction dir, rotates it in its own frame by the specified random amounts, then scales the rotated LookVector back up to be as long as dir originally was. In your example, dir would be mouse.Hit.p - o.

1 Like