How do I add in a spray offset in my gun system for raycasts?

How would I put an offset inside my raycast for it to act like spray?

heres what I have now

 local ServerRaycastVerify = workspace:Raycast(playerPos, DirectionServer, ServerParams)

the directionserver shoots towards the player but i wanna add an offset like +4 studs to random side depending if theyre moving etc, i just need to know how to implement the spray ontop of the direction already, thanks

Something like this

local Spread = 4

-- raycasting:
Direction + Vector3.new(math.random(-Spread, Spread), math.random(-Spread, Spread), 0)

There are obviously better examples and versions out there, this would be a very basic version of it.

1 Like

To improve on this, using CFrames usually works really well.

local direction = CFrame.LookAt(startpos, targetpos, Vector3.new(0,1,0))

Then multiply with another CFrame that has random angles applied to it.

local x, y = math.rad(math.random(-10, 10)), math.rad(math.random(-10, 10))

direction *= CFrame.Angles(x, y, 0)

local dir_vector = direction.LookVector.Unit * max_distance

dir_vector can now be used for a raycast.

2 Likes

Use Vector3.yAxis

I dont think its nessacary to use Unit on LookVector

I forgor. :skull:
LookVector should already be normalized.

Also that shortcut for the Y axis is super useful, baffled I haven’t found that one yet considering I looked at documentation not long ago.

1 Like

hey, how can i use cframes for raycasts? the direction in my script, its not a part just direction of the raycast goes to

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.