Raycasting function, yay!
Apparently, trying to shoot enemies will result in the entire code erroring, because “argument 1 is missing or nil” on the humanoid:TakeDamage() line
this is inside a module script incase that somehow makes it easier to debug
local function Raycasting(origin: Part, player: Player, hitPos: Mouse, weapon: Tool)
local HEADSHOT_DAMAGE = gunInfo[weapon.Name]["HEADSHOT_DAMAGE"]
local BODYSHOT_DAMAGE = gunInfo[weapon.Name]["BODYSHOT_DAMAGE"]
-- Raycast parameters.
local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Exclude
raycastParams.FilterDescendantsInstances = {player.Character}
raycastParams.IgnoreWater = true
local direction = (hitPos - origin.Position).Unit
local displacement = direction * gunInfo[weapon.Name]["MAX_DISTANCE"]
local result = workspace:Raycast(
origin.Position,
displacement,
raycastParams
)
local endPos = nil
-- Did the raycast hit something?
if result then
endPos = result.Position
local character = result.Instance.Parent
local humanoid = character:FindFirstChild("Humanoid")
if humanoid ~= players:GetPlayerFromCharacter(character) then
if result.Instance == character.Head then
humanoid:TakeDamage(HEADSHOT_DAMAGE) -- this will error
damageIndicatorEvent:FireClient(player, HEADSHOT_DAMAGE, humanoid)
else
humanoid:TakeDamage(BODYSHOT_DAMAGE) -- and so will this
damageIndicatorEvent:FireClient(player, BODYSHOT_DAMAGE, humanoid)
end
end
else
endPos = origin.Position + displacement
end
local tracer = Instance.new("Part")
tracer.Parent = workspace
tracer.Anchored = true
tracer.CanCollide = false
tracer.CanQuery = false
tracer.Transparency = 0.3
tracer.Color = Color3.new(0.960784, 0.666667, 0.156863)
dService:AddItem(tracer, 0.2)
local tracerLength = (endPos - origin.Position).Magnitude
tracer.Size = Vector3.new(0.07, 0.07, tracerLength)
tracer.CFrame = CFrame.lookAt(origin.Position + (endPos - origin.Position) / 2, endPos)
if weapon.AmmoType.Value == "NRG" then
tracer.Color = Color3.fromRGB(0,255,0)
end
end