Dustin Silk Dustin Silk - 1 year ago 44
Javascript Question

Check if vector is on other side of a line

Im trying to check if a vectors new position is crossing a given line.

I know the coordinates of the original vector, and its new position.
The line i want to check if it crosses is always perpendicular to the vectors original positions direction.
And the line is always the same distance from zero.

I'm using threejs so have access to all their math/vector functions. This is just in 2D however.

Here are two images to illustrate. I want to check if the black dot crosses the red line.
enter image description here

enter image description here

EDIT

If anyone ever needs to see the code for this, thanks to @beta's answer below. It was actually to stop a point from getting too close to the center of another object

canPointMoveTo(originalPos, newPos) {
const minDistance = 40;
const k = originalPos.clone().normalize();
const newDotProduct = newPos.dot(k);

return newDotProduct >= minDistance;
}

Answer Source

Call the distance from the origin to the line, D.
Call the vectors v0 and v1.
Take the old vector v0, normalize it, and call that vector k:

k = v0/|v0|

Now to find out which side of the line a vector is on, take its dot product with k and compare that value to D.

The vector "crosses the line" if and only if the old vector and the new vector are on different sides of the line:

{v0 . k > D and v1 . k < D} or {v0 . k < D and v1 . k > D}.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download