How to tell if a player is looking at a part?

I am having the problem of not being able to tell if a player is looking at a part since if they are looking at the part then I need the part to not go to the player. If you have any suggestions that would be great.

local myRoot = script.Parent:WaitForChild("HumanoidRootPart")
if game.Workspace.CurrentCamera.CFrame == myRoot.Position then
1 Like

You could have a look at Camera:WorldToViewportPoint(Vector3 world_point).

Its second return value is a boolean that determines whether or not world_point is within the viewport.

However it doesn’t do raycasting so even if terrain or parts are in the way it will still return true. Luckily on its API reference page a function to detect just this is provided, although it uses the old raycasting API.

Here is an example using the new API:

local camera = workspace.CurrentCamera

local function is_point_visible(world_point)
    local on_screen = select(2, camera:WorldToViewportPoint(world_point))

    if on_screen then
        local origin = camera.CFrame.Position
        local direction = world_point - origin
        local result = workspace:Raycast(origin, direction)

        if result then
            return false -- hit something so part is in the way
        return true
    return false

I’ve heard of that just wasn’t sure how efficient it was so I’ll try it out quickly.

It is not detecting correctly.

It is not working correctly as it is not printing anything.

You can use Vector3:Dot(Vector3), this returns a scalar between two positions. The first Vector3 can be your humanoidrootpart’s lookvector and the second can be the parts position subtracted by your position. A scalar smaller than 0 means its behind the player, a scalar bigger than 0 means its infront of the hrp

1 Like

Can you give me an example of how to use it?

Hi, there is a module for that, if you want to try here is the post: