How can I detect if a position is behind or in front of a part?

I have a script where it detects the player’s HumanoidRootPart position, and the player is either behind or infront of a part in workspace on the z axis. How do I detect if the player is in front of the part or behind it?

You could make use of raycasts

1 Like

I came across the issue myself, I’m sure there is a better way using some mathematics, but I don’t pay attention in class.

I was aware of how to find a point X studs infront of or behind something. Simply figure out if the location 2 studs infront is closer then the location 2 studs behind.

Red = Part
Black = Player
Green = Location 2 studs infront / behind

(Code I used in my fighting game to detect if an enemy is behind you, and therefore ignore blocking)

local function IsBehind(Target,AttackerLocation)
	local point1,point2 = (Target.CFrame + Target.CFrame.LookVector),(Target.CFrame + Target.CFrame.LookVector*-1)
	local mag1,mag2 = (point1.Position-AttackerLocation).Magnitude,(point2.Position-AttackerLocation).Magnitude
	return not (mag1 <= mag2)
end
4 Likes

Thanks, I appreciate both the replies. So I’m actually making this for a test to print if the player is behind the part or in front of it. I understand and noticed your code had an attacker position, the other player. How am I able to just make it so it prints if the player is behind or in front of a part in a while wait() do loop? Sorry if my question is kind of dumb, I’m just trying to make it a part instead of instancing the other player.

local function IsBehind(CharHRP,Part)
	local point1,point2 = (CharHRP.CFrame + CharHRP.CFrame.LookVector),(CharHRP.CFrame + CharHRP.CFrame.LookVector*-1)
	local mag1,mag2 = (point1.Position-Part.Position).Magnitude,(point2.Position-Part.Position).Magnitude
	return not (mag1 <= mag2)
end

--[[ Example code

while wait() do
	if IsBehind(Character.HumanoidRootPart,Part) then
		print("The part is behind the player")
	else
		print("The part is infront the player")
	end
end

Also, while wait() do loops are a code smell, considering avoiding their use
even the following below is much more efficient

while true do
	--Code
	task.wait()
end

]]--
5 Likes

Thanks for your help, I just tinkered around with the script you provided.

I also need help, how would it detect if the HumanoidRootPart is infront?

Use the new :Dot() method on Vector3s