Enemy FOV detection

Hey there! Ive recently been trying to create an enemy with pathfinding, and I’m trying to make it so the enemy has an FOV, where if it sees you in that FOV, then it will start chasing you with roblox’s pathfinding service, though I’m a little lost on how to get started. Any ideas/solutions? thanks!

Ive tried using raycasts already, though those are too precise, and I want it so it only detects players from the front of the rig, and it wont let me use blockcasts since I’m combining the direction of the raycast, a CFrame, with a vector3, the size.

you could make a big box in front of the enemy and use workspace:GetPartsBoundInBox() and detect if one of those parts is parented to the players character

Alright, I will try that right now! <3

2 Likes

Dude, a video that helped me a lot with this system you want to create. Basically it creates a field of view that identifies whether the chosen parts are in that field. This was the video I saw:

1 Like

You can use the dot product of the enemies Head or HumanoidRootPart LookVector and a Directional vector from it to the player to check if it’s within a certain angle.

This diagram is meant to show how the Dot product of these two vectors shows us how similar one vector is to another, the closer to 1 the number is the closer the player is to being exactly in the enemy’s look direction.

Local FOV = math.cos(math.rad(40)) -- Use degrees, coverts degrees to a number between -1 and 1 to use compare to the dot product. You could also just change this to a number between -1 and 1 instead like .5 which is 45 degrees

for _, player in pairs(game:GetService("Players"):GetPlayers()) do
    local character = player.Character or player.CharacterAdded:Wait() -- or just use "continue" to skip if their character hasn't been loaded if you don't want to yield the thread
    local direction = (character.HumanoidRootPart.Position - EnemyModel.Head.Position).Unit -- Get the direction from the Enemy to the Player
    local lookVector = EnemyModel.Head.CFrame.LookVector

    local dot = lookVector:Dot(direction) -- this is the dot product I mentioned.
    if dot > FOV then -- include all angles within a range to be in the enemies FOV
        print(player.Name .. " is in view.")
    end


end

This code might have little issuess I’m in a bit of a rush sorry!

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