Simple RayCast for horror game not working?

I’m working on a little thing for my horror game. So basically I’m trying to make a system so that whenever a player looks at the MainPart the script will wait for them to look away and then destroy the MainPart so whenever the players look at the MainPart again it will not be there, but it doesn’t do anything at all.


local MainPart = workspace:WaitForChild("ObjectPoltergeist1")
local Camera = game.Workspace.CurrentCamera
local Player = game:GetService("Players").LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()

local Params = RaycastParams.new()
Params.FilterType = Enum.RaycastFilterType.Exclude
Params.FilterDescendantsInstances = { Character }

local function Visibilty()

		local Vector, OnScreen = Camera:WorldToScreenPoint(MainPart.Position)

		if not OnScreen then
			return false
		end


		local Result = workspace:Raycast(Camera.CFrame.Position, (MainPart.Position - Camera.CFrame.Position).Unit * 500, Params)


		if Result and Result.Instance == MainPart then
			return true
		end
end

while true do
	local Visible = Visibilty()

	if Visible then
		repeat wait() until not Visible
		MainPart:Destroy()  
	end
	task.wait(0.01)
end

There is no errors in output or anything. Local Script is placed in StarterCharacterScripts. Ty for reading

The problem is that Visible is set to true when the part is looked at, then the script is locked inside this repeat wait() until not Visible loop since Visible will never change given the way you’ve scripted it.

My solution:

while true do
	local Visible = Visibilty()

	if Visible then
		repeat
			local Visible = Visibilty()
			task.wait()
		until not Visible
		MainPart:Destroy()  
		break -- I added this in here to stop the loop since you may as well if this is going to be the only thing in here.
	end
	task.wait()
end

The actual raycasting I did not change at all!

1 Like

Thanks a lot. I knew that it was something with the bottom part of the script and not the ray cast itself.

1 Like

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