How to detect if a player's head LookVector is looking at a NPC's head LookVector?

  1. What do you want to achieve? Keep it simple and clear!

I need to achieve where a player’s head LookVector is looking at a NPC’s head lookvector.

  1. What is the issue? Include screenshots / videos if possible!

The issue is, I don’t know how to check if a player’s head LookVector is looking at something else’s head LookVector.

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

I’ve tried many ways, but they don’t work at all…

Current code : https://i.imgur.com/z5SB1b4.png
Result: https://i.imgur.com/7NWA3To.png

Solutions on DevHub resulted of topic’s that weren’t what I was looking for, etc: Check if you can see someone’s head using workspace:WorldToScreenPoint, but it always activates no matter what side, but, I need to detect if a player’s head is looking at a specific side of a NPC’s head.

I’m not entirely sure what you are trying to achieve?

  • Do you want to see if the player is looking at the NPC?
  • Do you want to know if the player and NPC are looking at each other?
  • Do you want to know if the player and NPC are looking the same direction?
  • etc…

Can you please further elaborate?

1 Like

I want to know if the player and the NPC are looking at each other, front side, not the sides of the head, or behind of the head

If you want to determine if a vector is going towards a point, you can compare that vector to a vector of the same origin but pointing directly towards it and choose a range for which they can differ in degrees. Then do this twice, to compare from both perspectives. But it’s completely up to you to define what “looking at” means.

So the quickest way to do this is via the dot product.

local dot = npc.Head.CFrame.LookVector:Dot(character.Head.CFrame.LookVector)

if (dot > 0.5) then
	-- looking at each other
else
	-- not looking at each other
end

You can check out the article I linked for the explanation as to why this works.

I’d also rcmd adding a distance magnitude check to this as well to ensure the npc and your character are within a reasonable distance. That’s of course completely up to you. :grin:

13 Likes

Never knew that :Dot existed, thanks!

1 Like

I didn’t know :Dot existed either. This seems really helpful.

What would the number on “if (dot > 0.5) then” be if I wanted it for the player’s view instead of looking directly at each other?

You could Position instead of LookVector for the NPC:

local direction = CFrame.new(character.Head.Position, npc.Head.Position).LookVector
character.Head.CFrame.LookVector:Dot(direction)
1 Like