# How to activate something upon a player facing towards a part?

Hello! This is my first time posting on the developer forum, so hopefully I’m asking this in the right place.

What I’m essentially trying to do is to detect when the player is facing towards a part, and have something trigger upon looking at it. For context, I have some basic dialogue that I would like the player to say after looking at the part. I’ve heard of stuff like raycasting for this sort of thing, but I’m somewhat of a novice scripter, so I’m not super familiar with it.

Any help is appreciated. Thank you in advance!

1 Like

A player is facing towards a part when the direction from the player to the part and the direction the player is facing are similar.

Two directions are similar when the angle between them is small.

Therefore:

``````local playerPart = player.Character.HumanoidRootPart -- some part representative of the character
local part = workspace.Part
local angle = 30 -- angle in degrees in front of the player in which the part is considered to be "in front"

-- not a good function name, it's awkward and technically does not return an angle
function getAngleFacing(partA, partB)
local dirA = partA.CFrame.LookVector -- A's front direction
local dirB = (partB.Position - partA.Position).Unit -- direction from A to B. .Unit reduces the length to 1 stud.
end

angle = math.rad(angle / 2) -- halve it to 15°, actually 15° to either side = 30° total. also convert to radians
angle = math.cos(angle) -- no longer an angle, actually

while true do
if getAngleFacing(playerPart, part) < angle then
print("Player is facing part")
else
print("Player is not facing part")
end
wait(1)
end
``````

(Untested code)

This script will not consider a player laying on their back next to the part to be facing it because the front of the player is upward. But they will be considered facing it if they’re laying on their back under the part. You should make the script ignore the Y axis of the directions.

It will also consider the player to be facing the part regardless of distance. You will need to make it not trigger if the player and part are too far apart.
`(playerPart.Position - part.Position).Magnitude` is the distance between the two parts.

The dot product returns a number between -1 and 1 I’m pretty sure. You’d have to convert the dot product to an angle.
If you normalize the 2 vectors, then you can get the angle by using the fact that cos(angle) = dirA * dirB.

``````23:00:50.378  Players.That0nePixel.PlayerGui.MysteryTextGui.D1:197: attempt to index nil with 'CFrame'  -  Client - D1:197
At first I thought it was because `partA` wasn’t defined yet, but I substituted `playerPart` and the part that I want to be looked at, and it still gave the same error.