Hey developers,
Today I’m trying to well, make a gun that is half decent to use. (Most things I make a more so to improve my knowledge, so if you see me posting about completely different things that is why ) The current code I have is probably horrible to look at and things, but it does sort of work… heh.
The issues I’m facing here:
- Gun Lag / The “Bullets” are very laggy / do not react the same when switching from client to server testing. (Client fires the bullet instantly, Server takes a bit)
- The bullets are firing at rapid rates in which I do not know how to control… (First time I click, it fires one bullet, second 2, third 3, and so on…)
I’m using the code on raycasting on the wiki provided here.
Heres a gif of both problems occuring (note when I fired the gun, it took around 0.05 seconds or so to respond which is big difference than instantly, aswell as lagging behind my mouse which is a big nono.):
https://gyazo.com/8bbf38807fd9d8ba85a4bd12458ae073
Heres my Client-Sided code:
local player = game:GetService("Players").LocalPlayer
local mouse = player:GetMouse()
local isFiring = false
local cooldown = false
local damage = 3
local headshotMultiplier = 1.75
local function buttonDwn()
isFiring = true
while wait(.1) do
if isFiring == true then
game.ReplicatedStorage:WaitForChild("fireGun"):FireServer(mouse.Hit)
end
end
end
mouse.Button1Down:Connect(function()
buttonDwn()
end)
mouse.Button1Up:Connect(function()
isFiring = false
end)
And my Server-Sided code:
local event = game.ReplicatedStorage:WaitForChild("fireGun")
local damage = 3
local headshotMultiplier = 1.75
event.OnServerEvent:Connect(function(player, mouse)
local endPos = mouse.p
local startPos = player.Character.Head.CFrame.p
local CF = CFrame.new(startPos,endPos)*CFrame.Angles(math.rad(math.random(-1,1)),math.rad(math.random(-1,1)),0)
local DirVec = CF.LookVector
local ray = Ray.new(player.Character.Head.CFrame.p, (DirVec).unit * 999)
local part, position = workspace:FindPartOnRay(ray, player.Character, false, true)
local beam = Instance.new("Part", workspace)
beam.BrickColor = BrickColor.new("New Yeller")
beam.FormFactor = "Custom"
beam.Material = "Neon"
beam.Transparency = 0.6
beam.Anchored = true
beam.Locked = true
beam.CanCollide = false
local distance = (player.Character.Head.CFrame.p - position).magnitude
beam.Size = Vector3.new(0.3, 0.3, distance)
beam.CFrame = CFrame.new(player.Character.Head.CFrame.p, position) * CFrame.new(0, 0, -distance / 2)
game:GetService("Debris"):AddItem(beam, 0.05)
if part then
local humanoid = part.Parent:FindFirstChild("Humanoid")
if not humanoid then
humanoid = part.Parent.Parent:FindFirstChild("Humanoid")
end
if part.Name == 'Head' and humanoid then
humanoid:TakeDamage(damage * headshotMultiplier)
end
if humanoid then
humanoid:TakeDamage(damage)
end
if part.Name == 'Handle' and part.Parent:IsA('Hat') or part.Parent:IsA('Accessory') and humanoid then
humanoid:TakeDamage(damage * headshotMultiplier)
end
end
end)
Thank you!!