Raycasting help - Continuous result

Raycasting Script

Local script:

local players = game:GetService("Players")
local p = players.LocalPlayer
local function hasSeen()
	local runS = game:GetService("RunService")
	local rayPart = p.Character:WaitForChild("HumanoidRootPart")
	local rayOrigin = rayPart.Position
	local lookDirection = rayPart.CFrame.LookVector * Vector3.new(0,0,100)
	local rayParams = RaycastParams.new()
	rayParams.FilterDescendantsInstances = {workspace.Glass}
	rayParams.FilterType = Enum.RaycastFilterType.Blacklist
	local raycastingResult = workspace:Raycast(rayOrigin,lookDirection,rayParams)
	
	if raycastingResult then
		print("hit")
		local hit = raycastingResult.Instance
		if hit.Name == "Paint" then
			print("hit the painting")
			
		end
	end
end

p.CharacterAdded:Connect(hasSeen)

More information

This script is pretty straightforward which I made while referring to this article on the Wiki and this page. Whenever the player’s character spawns into the game, a ray is casted from the part “HumanoidRootPart” located on the player’s character.

Although the script works perfectly as how it should, I want to make it so the ray doesn’t exist once, I want it to exist continuously, so it will print whenever the player looks at the painting which is the ideal outcome. Side note: I might eventually add a distance property so its not like rays have to constantly be created even outside the necessary range which may negatively impact on performance if that is the case, maybe you guys can enlighten me on that also. Would be much appreciated! P.S. feel free to critique me on my methods, would help me a lot.

2 Likes

Simple, use a while loop or RunService.Heartbeat Connection - which continues during the Character’s lifetime (you can check if a Character is destroyed when it’s Parent is nil) - and keep firing the Raycast within it.

ie.

local Connection do --// Clean do block syntax; limits the Connection to the scope and allows you to use it within
    Connection = runS.Heartbeat:Connect(function()
        if (not p.Character.Parent) then --// nil acts as falsey, not nil = true
            Connection:Disconnect(); --/ Disconnect the Connection and stop it from running
        end

        --// Raycast!
    end)
end
3 Likes

I was thinking that would work. Would that have an affect on the player’s performance would you think to have it constantly firing the Raycast? If so, would you think my idea of tracking the player’s distance from the painting would work in mitigating performance issues or would you believe this to be minor?

1 Like

Raycasts are highly optimised and easy to use, I fire many every Heartbeat to detect when a Player walks in-front of an NPC and have 0 issues on performance.

1 Like

That’s brilliant. Thank you, @ReturnedTrue!

1 Like