I have a gun script with a set max distance, but for some reason the gun raycasts/shoots past the max distance. And also, when I shoot at the sky it doesn’t return a raycastResult. Can anyone help??
local tool = script.Parent
local fireEvent = tool.FireEvent
local firePoint = tool.Muzzle.Attachment
local debris = game:GetService("Debris")
local config = script.Parent.Configuration
local maxdist = config.MaxDistance.Value
local spread = config.Spread.Value
local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
raycastParams.IgnoreWater = true
local function onEquip()
raycastParams.FilterDescendantsInstances = {tool, tool.Parent}
end
local function fire(mousePoint)
local fireDistance = (tool.Muzzle.Attachment.WorldPosition - mousePoint).Magnitude
local finalPoint = Vector3.new((mousePoint.x)+(math.random(-(spread/10)*fireDistance,(spread/10)*fireDistance)),(mousePoint.y)+(math.random(-(spread/10)*fireDistance,(spread/10)*fireDistance)),(mousePoint.z)+(math.random(-(spread/10)*fireDistance,(spread/10)*fireDistance)))
local rayDirection = (finalPoint - tool.Muzzle.Attachment.WorldPosition).Unit * maxdist
local raycastResult = workspace:Raycast(tool.Muzzle.Attachment.WorldPosition, rayDirection)
if raycastResult then
local part = Instance.new("Part")
part.Parent = workspace
part.Anchored = true
part.Position = raycastResult.Position
print("Instance:", raycastResult.Instance)
print("Position:", raycastResult.Position)
print("Distance:", raycastResult.Distance)
print("Material:", raycastResult.Material)
print("Normal:", raycastResult.Normal)
end
end
fireEvent.OnServerEvent:Connect(function(player, mousePoint)
fire(mousePoint)
end)
tool.Equipped:Connect(onEquip)
for when it doesnt return raycastResult just replace the result distance with maxDistance.
raycast result is returning only in case if it hit something