How To Make An Event Happen When A Player Sees An Object

I’m Making A Horror Game Where A Creature Will Chase You Down If You See It, I Want To Know What I Can Do To Make This Happen When The Creature Is Seen(I Don’t Want The Event To Happen If The Creature Is Not Within Frame Of The Camera.) I’ve Tried Making A Constant Raycast To The HumanoidRootPart Of The Creature To The Camera And To Fire An Event When The Camera Sees The HumanoidRootPart, But I Can’t Get The Event To Fire Without An Error Occuring.

Try this:

This function uses the direction from the camera to the creature and the camera’s view to determine if the creature is potentially within view. Then, it uses a raycast to check for any obstacles between the camera and the creature.

This code also is only for one creature, If you have multiple, you might want to pass the creature instance in the parameters of the isCreatureVisible function.

local camera = workspace.CurrentCamera
local creature = workspace.Creature.MainPart -- whatever the creature is, make this a part of the creature. Like the head.
local player = game.Players.LocalPlayer

local function isCreatureVisible()
    local directionToCreature = (creature.Position - camera.CFrame.Position).unit
    local dot = camera.CFrame.LookVector:Dot(directionToCreature)
    
    if dot > math.cos(math.rad(70 / 2)) then
        -- Creature could be in view. now check for obstacles, like walls in front of the player and the creature
        local ray = Ray.new(camera.CFrame.Position, directionToCreature * 1000)
        local hit = workspace:FindPartOnRayWithIgnoreList(ray, {player.Character})
        if hit and hit:IsDescendantOf(creature.Parent) then
            return true
        end
    end
    return false
end

while true do 
    wait(1) -- Checks every 1 second. Might want to change this depending on how fast creatures move.
    if isCreatureVisible() then
        print("Creature seen! Ahhhhhhhh!!!!!")
    end
end
2 Likes

Thank You! It Worked Perfectly.

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