How would i go about checking if a player can be seen by a bot?

heres a reference image i made
ref drawing
so i want to know if a player is inside that radius, i know you can use raycasts but i have no idea how to go about it

1 Like

You can simply set raycast from bot humanoidrootpart to player humanoidrootpart and check if there parts on ray.

There script for you:

local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")

local bot = Workspace:WaitForChild("Bot")

local maxDistance = 50

-- Function to perform the raycast
local function performRaycast(botRootPart, playerRootPart)
	-- Set up raycast parameters
	local raycastParams = RaycastParams.new()
	raycastParams.FilterType = Enum.RaycastFilterType.Exclude
	raycastParams.FilterDescendantsInstances = {botRootPart.Parent, playerRootPart.Parent}

	-- Calculate the direction vector
	local direction = playerRootPart.Position - botRootPart.Position

	-- Perform the raycast
	local result = Workspace:Raycast(botRootPart.Position, direction, raycastParams)

	-- Check if the raycast hit anything
	if result then
		print("Raycast hit:", result.Instance:GetFullName())
		return false
	else
		print("Clear line of sight")
		return true
	end
end

while task.wait(1) do
	local closest
	local lastDistance = math.huge
	
	-- get nearest player
	for _,v in pairs(game:GetService("Players"):GetPlayers()) do
		local magnitude = (bot:FindFirstChild("HumanoidRootPart").Position - v.Character.HumanoidRootPart.Position).magnitude
		if magnitude < lastDistance and magnitude <= 50 then
			closest = v
		end
		lastDistance = magnitude
	end
	
	if closest then
		performRaycast(bot:FindFirstChild("HumanoidRootPart"),closest.Character:FindFirstChild("HumanoidRootPart"))
	end
end

POV: When you use ChatGPT. ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎

First of all: it is not forbidden to use chat gpt anywhere.

Secondly: I put my own code in the gpt chat, which had an error in the calculations of raycast. I left the lines with the print from chat gpt so that the author of the post could read the code more conveniently and clearly

1 Like

ok ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎

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