Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How would I tell if a player is behind another player?

Like to check if someone was in front of, or behind another person. Would it be something like this?

function isBehind(plr1,plr2)
if plr1.Torso<plr2.Torso.CFrame.lookVector then
return true
end
end

2 comments

0

You would probably have to do raycasting.

0

I am terrible at RayCasting.

1 answer

✓ Accepted answer

There's more or less two ways to do this, and they both actually amount to the same thing.

What you have is sort of what it will look like, except that you wrote is just made up and not actually based on any of the math.


Math approach:

To determine to what extent a point is in a given direction, we use the Dot Product.

The direction we want is one part's lookVector; the direction from one player to the other is the difference of their Positions:

-- using A and B as parts (the player torsos):
-- Check if B is in front of A

forward = A.CFrame.lookVector
displacement = B.Position - A.Position -- (direction)

amountForward = forward:Dot(displacement)

if amountForward > 0 then
	-- Forward
else
	-- Behind
end

Or, we can use the CFrame and its Object Space.

Object space refers to using some object as the origin (so (0,5,0) is 5 studs "up" where "up" is the top of a brick; (0,0,0) would be the position of the brick rather than the origin)

whereB = A.CFrame:pointToObjectSpace( B.Position )
if whereB.z > 0 then
	-- Behind
else 
	-- In front
end

3 comments

0

Are you a Wiki writer? Because you're surely good at ROBLOX's API and are a GREAT teacher! Thanks!

0

I am a Wiki writer but I almost never write on the Wiki.

0

You should, because you're an awesome teacher. No one on here explains things as good as you did. Good job.

This discussion is preserved as it was. New answers, comments, and votes are closed.