Raycast not working when the player is facing a specific direction

I am trying to recreate a Baldi’s Basics like AI inside of Roblox. It mostly works except when it is time to chase the player.

Facing different ways tricks the raycast somehow, and you can be completely undetectable.

I have looked at other forum posts and tried their solutions, however I have not came to a conclusion as of now.

Here is the part of the script that handles the raycasting:

function CheckIfCanChase(player: Player): boolean
	local rParams = RaycastParams.new()
	rParams.FilterType = Enum.RaycastFilterType.Exclude
	rParams.FilterDescendantsInstances = {Baldi}
	
	local rayDirection = player.Character.HumanoidRootPart.Position - Baldi.Head.Position
	local raycastresult = workspace:Raycast(Baldi.Head.Position, rayDirection)

	if raycastresult.Instance then
		local foundPlayer = PlayersService:GetPlayerFromCharacter(raycastresult.Instance.Parent)
		if foundPlayer == player then
			print("looking at player")
			chasedPlayer = player
			alreadyChasing = true
			task.spawn(function()
				ChasePlayer(player)
			end)
			return true
		end
	end
	return false
end
while true do
	wait()
	if alreadyChasing then
		local rParams = RaycastParams.new()
		rParams.FilterType = Enum.RaycastFilterType.Exclude
		rParams.FilterDescendantsInstances = {Baldi}

		local rayDirection = chasedPlayer.Character.HumanoidRootPart.Position - Baldi.Head.Position
		local raycastresult = workspace:Raycast(Baldi.Head.Position, rayDirection)

		if raycastresult.Instance then
			local foundPlayer = PlayersService:GetPlayerFromCharacter(raycastresult.Instance.Parent)
			if foundPlayer ~= chasedPlayer then
				print("lost player")
				ServerStorage.Baldi.CurrentBaldiPhase.Value = "Limbo"
				MainScript.ignoreHearEvents = false
				alreadyChasing = false
			end
		end
	else
		for _, player in pairs(PlayersService:GetPlayers()) do
			CheckIfCanChase(player)
		end
	end
end

Any help in the right direction would be appreciated.

Your character’s accessories are messing up the raycast result, causing it to hit the accessory handle which is not a direct child of your character. If you want the raycast to ignore accessories, you’ll need to set the CanQuery property of the accessory handles to false.
CanQueryex

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