Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to tell if something is behind an object or in front or to the side of an object?

Asked by
Tizzel40 243 Moderation Voter
4 years ago

um... the Title should be strait forward so uh... yea!

How do you find out if something is in front, to the side, or behind an object?

Im guessing math is involved!!!?????

1 answer

Log in to vote
3
Answered by 4 years ago
Edited 4 years ago

You can use the dot product for this.

Say you have objectA and objectB. You want to know if objectB is in front of, behind or to the side of objectA.

First get the vector from objectA to objectB. We'll call this offsetVector:

local offsetVector = objectB.Position - objectA.Position

We want to convert this to a unit vector, like so:

offsetVector = offsetVector.Unit

You can then use the dot product of objectA's look vector and our offset vector to see if objectB is behind or in front of objectA:

local dot = objectA.CFrame.LookVector:Dot(offsetVector)

dot will be a number between -1 and 1. If dot is positive, then objectB is in front of objectA. If dot is negative, then objectB is behind objectA. The closer dot is to zero, the closer objectB is to the left or right of objectA.

To picture this, you can imagine a line going through the center of objectA perpendicular to it's look vector, with everything in front of objectA on one side of the line, and everything behind objectA on the other side of the line. If objectB is in front of this line then dot will be positive, if it is behind the line then dot will be negative, and if it is on the line then dot will be zero.

I'm not sure if that was clear, but I hope it helps.

Ad

Answer this question