Determine if target/player is in front, back, side of NPC

My current implementation I detect player(s) with X distance and then check line of site (raycasting)

This looks to be working as expected, but I need to be able to determine if the target/player is in front, back or to the side of the NPC.

Struggling the right combinations or values/equation leverage (LookVector, CFrame, Position).

The point in the code where the logic needs to execute has the following:
Target/Player
NPC
raycastResult.Instance

I feel like I’m missing something obvious or just need to step away and come back to it.

Thanks for any help.

voss.

2 Likes

I may be reading this wrong but if you are only trying to fiind which way the NPC is facing at the player just cast a ray in each direction from the torso and if it hits a player then we know they hit the NPC is facing the player from that direction

You could probably just find the vector between the target and the NPC and then find the dot product between the lookvector and the vector to the target and compare that to the dot product between the right vector and the target vector, etc. and compare which dot product is the greatest.

image

image

The more ‘parallel’ the vectors are, the bigger the dot product is.

Hello! Instead of using RayCasting, have you tried using DotProduct? If you don’t know how to use it, there is a great YouTube tutorial that can help.

8 Likes

Thanks everyone that’s exactly what I needed