Search code examples
javamath3dvectorjmonkeyengine

Check if a vector is between two others


I have a "box" made out of two three-dimensional vectors. One for the front-lower-left corner and one for the back-upper-right corner.

Are there any simple way to check if a third three-dimensional vector is anywhere inside this "box"?

First i wrote simething like (psuedo):

p = pointToCompare;
a = frontLowerLeft;
b = backUpperRight;

if(p.x >= a.x && p.x <= b.x && p.y >= a.y ...

But that does only work if all coordinates are positive, which they won't always be. Should i do something like the above, or are there any better/simpler way to do this calculation?

If you would like to know, this is the Vector and it's method i'm using: http://www.jmonkeyengine.com/doc/com/jme/math/Vector3f.html


Solution

  • If you want to make it a little more robust, you could make it invariant to the position of the corners:

    if (a.x <= p.x && p.x <= b.x || b.x <= p.x && p.x <= a.x) {
      // similar to the y- and z-axes.
    }
    

    A more intutive (but slightliy slower) variant would be to use min/max on each axis:

    if (Math.min(a.x, b.x) <= p.x && p.x <= Math.max(a.x, b.x)) {
      // ...
    }