local replicatedStorage = game:GetService("ReplicatedStorage")
local uis = game:GetService("UserInputService")
local gun = script.Parent
local gunAmmo = gun:GetAttribute("AmmoCount")
local gunAmmoSet = 7
local canReload = true
local fireGunEvent = replicatedStorage.FireGun
local gunDebounce = false
local debounceTime = gun:GetAttribute("Cooldown")
local player = players.LocalPlayer
local mouse = player:GetMouse()
gun.Equipped:Connect(function()
canReload = true
uis.InputBegan:Connect(function(input, _GameProccessed)
if _GameProccessed then return end
if input.KeyCode == Enum.KeyCode.R and canReload == true then
gunAmmo = gunAmmoSet
print("reloading!")
end
end)
end)
gun.Unequipped:Connect(function()
canReload = false
if canReload == false then
print("gun cannot be reloaded")
end
end)
gun.Activated:Connect(function()
if not gunDebounce and gunAmmo >= 0 then
print(gunAmmo)
gunAmmo -= 1
gunDebounce = true
local startPos = gun.Barrel.MuzzleFlashAttach.Position
local endPos = mouse.Hit.Position
print("gun fired")
fireGunEvent:FireServer(gun, startPos, endPos)
task.wait(debounceTime)
gunDebounce = false
end
end)
and my server script
local fireGunEvent = replicatedStorage.FireGun
fireGunEvent.OnServerEvent:Connect(function(player, gun, startPos, endPos)
local MaxDistance = gun:GetAttribute("MaxDistance")
local Damage = gun:GetAttribute("Damage")
local direction = (endPos - startPos).Unit * MaxDistance
local raycastRes = game.Workspace:Raycast(startPos, endPos - startPos)
if raycastRes then
print(raycastRes)
local hitChar = raycastRes.Instance.Parent
local humanoid = hitChar:FindFirstChild("Humanoid")
if humanoid then
if hitChar.Name ~= player.Character.Name then
humanoid.Health -= Damage
end
end
end
end)
This position is not where you think it is, so your ray is not starting where the gun is. Attachment.Position is the translation of the attachment relative to its parent. You probably need this line to change to this:
local startPos = gun.Barrel.MuzzleFlashAttach.WorldPosition
Consider adding some debug visualization. Like you can create a LineHandleAdornment locally, set its Parent and Adornee to game.Workspace.Terrain (convenient because it’s always at 0,0,0) and then set the LineHandleAdornment.CFrame = CFrame.new(startPos, endPos) and LineHandleAdornment.Length = (endPos-startPos).Magnitude. Then, you’ll see where the ray is actually starting and pointing.