How do I check if a player is infornt of another play like facing each other

Im trying to make a script that detecting when a player is facing another player

1 Like

You could use raycasting.

You can cast a ray say 50 studs in front of their face.

local result = workspace:Raycast(player.Character.Head.Position, player.Character.Head.CFrame.LookVector*50)

if result then
    local target_player = Players:GetPlayerFromCharacter(result.Instance.Parent)

    if target_player then
        print(target_player)
        print(result.Position)
    end
end

Basically, it is casting a ray at the head’s position, then 50 studs in front.

From there it checks if the ray actually hit anything. If so it tries getting a player from the part’s parent.

If there is a player it prints the name of the player as well as the position where the ray hit.

1 Like

You need to get the direction the player is looking at using:

local looking = Player1.Character.HumanoidRootPart.CFrame.lookVector

And you want to get the direction of the other player, say Player2, from Player1:

local direction = (Player2.Character.HumanoidRootPart.Position - Player1.Character.HumanoidRootPart.Position).Unit

You’ll have to use the dot product and we can find the angle between both vectors. The dot product’s calculation is: dot = math.cos(theta) * a.magnitude * b.magnitude. Theta is the angle and we can find it from the equation by doing: theta = math.acos(a • b / a.magnitude * b.magnitude).

Putting in all together, we get:

local dot = looking:Dot(direction)
local angle = math.acos(dot) -- we don't need to divide by 1 * 1, since it's redundant
angle = math.deg(angle) -- converting to degrees because it's in radians

You just need to check if the angle is less than your specified maximum value, and you can see if the player is in front of another

18 Likes