im currently coding a gun system with raycasting and i was wondering how i would make spread so the gun wasnt so accurate?
heres the code im using:
ShootRem.OnServerEvent:Connect(function(player,mousePos)
local raycastParams = RaycastParams.new()
raycastParams.FilterDescendantsInstances = {player.Character} -- makes so player cant shoot self
raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
local rayResult = workspace:Raycast(script.Parent.Handle.Position, (mousePos - script.Parent.Handle.Position)*300,raycastParams) -- gun length
if rayResult then
local hitPart = rayResult.Instance
local model = hitPart:FindFirstAncestorOfClass("Model")
if model then
if model:FindFirstChild("Humanoid") then
print("Hit: ".. hitPart.Name)
if hitPart.Name == "Head" then
local damageDelt = math.random(28,39)
model.Humanoid.Health -= damageDelt
print("-"..damageDelt)
else
local damageDelt = math.random(16,21)
model.Humanoid.Health -= damageDelt
print("-"..damageDelt)
end
end
end
end
end)
There have been a lot of posts that explain this.
I searched ‘raycast random spread’ and got a few hits. You can try similar search terms like ‘random gun spread’ or ‘aim bullets randomly’.
I guess depending on the distance between the mouse hit position and the origin you get a number and then you make a new direction with a random offset on the mouse hit position, and then fire a ray with that direction and you can spawn a part on the ray hit to see if it gives an offset? The number offset should just be the distance between divided by a certain number * inaccuracy. I think it would work if you just used math.random and then did in the thing (-accuracy, accuracy) for every vector.
So basically, you just get the mouse hit position using mouse.Hit.Position after getting the players mouse and then you add a vector3 to it and then cast the ray to it.
Here is some code for it that might help you a little
local inaccuracy = 2
local mouse = --whatever your players mouse is
mouse.Button1Down:Connect(function()
local mousepos = mouse.Hit.Position
local origin = --gun barrel or stuff
local distancebetween = (origin - mousepos).Magnitude
local accuracy = distancebetween/100*inaccuracy --you can change this to get better or worse accuracies
--raycast stuff and more
end
local mag = (cursor.Hit.p-tool.Hole.Position).magnitude
local rndm = Vector3.new(math.random(-(Spread/10)*mag,(Spread/10)*mag),math.random(-(Spread/10)*mag,(Spread/10)*mag),math.random(-(Spread/10)*mag,(Spread/10)*mag))
put this in your local script where you would make fire function
then when you will fire the function to server write also +rndm in fireserver function