How to set max distance on a raycast?

Hello, i am trying to figure out how to make a max distance for a raycast, say the distance is set to 30 studs. Any time the raycast is hit to anywhere <30 studs from the player, it will work, but >30 will not work. Heres my code

local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local val: BoolValue = char:WaitForChild("unstunned")
local tool = script.Parent
local event = script:WaitForChild("Fire")
local cd = false
local cdTime = 5
local equipped = false
local objectFound = false
local selectedHighlight = Instance.new("Highlight")
selectedHighlight.Parent = workspace.Fx
selectedHighlight.FillColor = Color3.new(255,255,255)
local enemy = nil

tool.Activated:Connect(function()
	if cd == false and val.Value == true and script.isSelected.Value == true and workspace.globalCooldowns.InfiniteVoid.Value == false and char.Meter.Value == 100 then
		cd = true
		
		event:FireServer(enemy)
		
		wait(cdTime)
		cd = false
	end
	
end)



function mouseRayCast()
	local mousePos = game:GetService("UserInputService"):GetMouseLocation()
	local mouseRay = workspace.CurrentCamera:ViewportPointToRay(mousePos.X, mousePos.Y)
	local rayParams = RaycastParams.new()
	rayParams.FilterDescendantsInstances = {plr.Character}
	rayParams.FilterType = Enum.RaycastFilterType.Exclude
	local rayResult = workspace:Raycast(mouseRay.Origin, mouseRay.Direction * 100000, rayParams)
	
	
	return rayResult
end


tool.Equipped:Connect(function()
	if equipped == false then
	equipped = true
	end


while true do
	if equipped == false then return end
	
		local beam = mouseRayCast()
	if not beam then
		objectFound = false
	else
		objectFound = true
	end

if beam.Instance.Parent:FindFirstChild("Humanoid") and objectFound == true then
	script.isSelected.Value = true
	selectedHighlight.Adornee = beam.Instance.Parent
			enemy = beam.Instance.Parent
else
	script.isSelected.Value = false
	selectedHighlight.Adornee = nil
			enemy = nil
	
end
task.wait()
end

end)

tool.Unequipped:Connect(function()
	if equipped == true then
	equipped = false
	selectedHighlight.Adornee = nil
	script.isSelected.Value = false
	end
end)

If anyone helps, that will be greatly appreciated! Thanks!

Just set this to 30.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.