开发者

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 y开发者_如何转开发ou 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


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)) {
  // ...
}


Here is a general solution for a box that may not be even right angles, i.e. a generic parallelepiped.

The trick here is to find the transformation that transforms your box into the unit cube. If you then throw your vector that you want to test through this transformation, you would just need to check that X, Y and Z all lie between zero and one.

Consider a corner point on your box to be your origin. Let's call that K. Now construct your three principal axes P Q R as the vectors that extend along the three edges that touch this point.

Now any point in three-dimensional space can be represented as K + aP + bQ + cR. Moreover, there is only one (a, b, c) that satisfies.

If you can determine (a, b, c), you simply need to check that each is between 0 and 1.

If anyone is interested in the matrix math, give me a bell!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜