Search code examples
javapositionxyz

How can i check if a Vector3 (x,y,z) is between 2 other Vector3's in Java?


I want to make a protection plugin for a Minecraft server software and I want to work with Vector3. I want to check if a Vector3 is between 2 Positions (Vector3).

The Vector3 has got the values: x, y, and z. How can I check now if a Vector is between 2 others?

Vector3 pos1 = new Vector3(100, 10, 100);
Vector3 pos2 = new Vector3(10, 100, 43);
Vector3 vector3tocheck = new Vector3(60, 23, 1); // it should be between the 2 positions

public boolean isInTwoVectors(Vector3 pos1, Vector3 pos2, Vector3 vector3tocheck) {
// Here idk how to continue.
}

I expect the result if it is in the two positions or not.


Solution

  • public boolean isInTwoVectors(Vector3 pos1, Vector3 pos2, Vector3 check) {
        int minX = Math.min(pos1.x, pos2.x);
        int maxX = Math.max(pos1.x, pos2.x);
        int minY = Math.min(pos1.y, pos2.y);
        int maxY = Math.max(pos1.y, pos2.y);
        int minZ = Math.min(pos1.z, pos2.z);
        int maxZ = Math.max(pos1.z, pos2.z);
        return check.x >= minX && check.x <= maxX && check.y >= minY && check.y <= maxY
            && check.z >= minZ && check.z <= maxZ;
    }
    

    Simply, check all the x, y, and z bounds for whether the vector lies within. For the record, in your example, the given vector would not be within the bounds, because its z-value is out of bounds (outside of [43,100]). In this case (not caring about z-value), you'd only check x- and y-values, as so:

    public boolean isInTwoVectorsXY(Vector3 pos1, Vector3 pos2, Vector3 check) {
        int minX = Math.min(pos1.x, pos2.x);
        int maxX = Math.max(pos1.x, pos2.x);
        int minY = Math.min(pos1.y, pos2.y);
        int maxY = Math.max(pos1.y, pos2.y);
        return check.x >= minX && check.x <= maxX && check.y >= minY && check.y <= maxY;
    }
    

    Alternatively, maybe you actually mean something like this or this?