Ray ignores if the part that detected by ray stand in front of other part

I am making a system that the train detects the nearest semaphore and it is detected by ray and the problem is that if something gets on the tracks, for example there is a station, and after the station there is the semaphore itself, then ray will ignore the semaphore. Here is the code:

function detectNearestLight()
	local seat = script.Parent.Floor


	local rayOrigin = seat.Position
	local rayDirection = seat.CFrame.LookVector * distance -- Adjust the length of the ray as needed

	local raycastParams = RaycastParams.new()
	raycastParams.FilterDescendantsInstances = {script.Parent.Parent} 
	raycastParams.FilterType = Enum.RaycastFilterType.Blacklist

	local raycastResult = workspace:Raycast(rayOrigin, rayDirection, raycastParams)

	if raycastResult then
		local hitPart = raycastResult.Instance
		if hitPart then
		if hitPart.Name == "trainlightdetector" then
	
			if player then
				if player.PlayerGui:FindFirstChild("GuiS") then
					local remote = player.PlayerGui.GuiS.RemoteEvent:FireClient(player,"NearestLight",getdistance(seat.Position,raycastResult.Position),tostring(hitPart.LightColor.Value))
				end
			end
		
			
					end	
	end
		
	end
end

It’s most likely because your ray’s length is too large.

The distance variable determines the length of the ray. If it’s too large, the ray might skip over the part.

the problem that the length specially that it is far away to detect the semaphore

If the station is blocking your raycast, you could use an include list instead of an exclude list and in the list include all of your semaphores.

Ex:

raycastParams.FilterType = Enum.RaycastFilterType.Include
raycastParams.FilterDescendantsInstances = --[Get a list of all your semaphores]

You could get a list of your semaphores by their name or by adding tags to them and using CollectionService:GetTagged([Your tag name])

1 Like

thank you very much it helps!–

1 Like

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