How would I detect when a ray leaves a part?

Hi there!

I’m currently using a simple raycasting system that shoots a ray from a player’s head. It will enable a proximity prompt every time it detects that part.
However, I would also like the proximity prompt to disable every time the ray goes away from the prompt.
What is the easiest way in doing this? Here is my script for the raycasting system

local char = game.Players.LocalPlayer.Character
local Head = char.Head
local rs = game:GetService("RunService")

rs.RenderStepped:Connect(function()
	local ray = Ray.new(Head.CFrame.p, Head.CFrame.LookVector * 100)
	local part = workspace:FindPartOnRay(ray)
	
	if part then
		if part.Name == "PromptEnabler" then
			part:FindFirstChild("ProximityPrompt").Enabled = true
		end
	end
end)

Any help is appreciated
Thanks! :slight_smile:

local char = game.Players.LocalPlayer.Character
local Head = char.Head
local rs = game:GetService("RunService")

local lastpart = char.head -- just to prevent errors becuz dude doesnt allow u to compare a part with a nil
rs.RenderStepped:Connect(function()
	local ray = Ray.new(Head.CFrame.p, Head.CFrame.LookVector * 100)
	local part = workspace:FindPartOnRay(ray)


	if part ~= lastpart then
		--ray moved away
	end
lastpart = part
end)

I tried it and it doesn’t work
I’m pretty sure it’s because lastpart is always being updated so part will always be equivalent to lastpart 100% of the time

lol thats because you put it before the if statement, put it behind the if statement

1 Like

Same thing, it’s still not working

Nevermind referenced the wrong thing lol
Thanks for your help! :slight_smile:

Final script btw for anyone that stumbles upon this post

local char = game.Players.LocalPlayer.Character
local Head = char.Head
local rs = game:GetService("RunService")

local lastpart = char.Head
rs.RenderStepped:Connect(function()
	
	local ray = Ray.new(Head.CFrame.p, Head.CFrame.LookVector * 100)
	local part = workspace:FindPartOnRay(ray)
	
	if part then
		if part.Name == "PromptEnabler" then
			part:FindFirstChild("ProximityPrompt").Enabled = true
		end
	end

	if part ~= lastpart then
		if lastpart then
			if lastpart.Name == "PromptEnabler" then
				lastpart:FindFirstChild("ProximityPrompt").Enabled = false
			end
		end
	end
	
lastpart = part
end)
1 Like