Stopping Raycast at Certain Distance

I was wondering if there is a way to stop a Raycast at a certain distance, I’m aware Result.Distance is a thing, but I was curious if I could stop it at lets say 50 studs if it doesn’t detect a brick/wall in the way.

Example being that if you are 30 studs away from the wall, the Raycast will get the position of the wall, but if you’re 100 studs away from the wall it will only stop at the 50 stud mark and get that position where the raycast stops.

local slamEvent = script.Parent.Slam
local tweenService = game:GetService("TweenService")
local slamDebouce = false
local setDistance
slamEvent.OnServerEvent:Connect(function(Player, rCastDirection)
	print(rCastDirection)
	if slamDebouce == false and rCastDirection ~= nil then
		slamDebouce = true
		local filteredParts = Player.Character:GetChildren()
		local rCastOrgin = hit.Parent:FindFirstChild("HumanoidRootPart").Position
		local rCastResult = workspace:Raycast(rCastOrgin, rCastDirection)

		originalDistance = hit.Parent:FindFirstChild("HumanoidRootPart").Position
		local tweenInfo = TweenInfo.new(
			0.4,
			Enum.EasingStyle.Linear,
			Enum.EasingDirection.Out,
			0,
			false,
			0
		)
		local tween = tweenService:Create(hit.Parent:FindFirstChild("HumanoidRootPart"), tweenInfo, {Position = rCastResult.Position})
		local returnTween = tweenService:Create(hit.Parent:FindFirstChild("HumanoidRootPart"), tweenInfo, {Position = originalDistance})
		Player.Character:WaitForChild("Humanoid").WalkSpeed = 0
		tween:Play()
		wait(0.4)
		returnTween:Play()
		wait(0.4)
		Player.Character:WaitForChild("Humanoid").WalkSpeed = 16
		slamDebouce = false
		
	end
end)

This is an example of my script and I was wondering if anybody could assist me and lead me in the right direction. Thank you in advance!

2 Likes

Doesnt the Direction also dictate the raycasts length?

looks like it does

and then use

raycastResult.Position

to get the position even if it doesnt hit anything

From what I’ve tested with, when things are away from the distance/length it just gives me an attempt to index nil rather than an actual position it stopped at.

youre right… you could maybe take the position youre shooting from and multiply the vlaue of its direction to where the raycast would end up to get the position

if raycast then
 -- do some work
else
    local endposition = (CFrame.new(ray origin, ray origin + ray direction) 
* CFrame.new(0,0,-distance)).Position
end
2 Likes

Thank you so much! This helped out a lot.

1 Like

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