Perform a AABB hit test in 3D

Is it possible to do a point hit test on a axis aligned bounding box after things like rotation are applied?

Here is one of my current attempts, but i’m not sure if i’m after something that is possible at all.


int w = 200;
int h = 200;

void setup() {
  size(600, 600, P3D); 
}

void draw() {
  background(30);
  
  pushMatrix();
  translate(width/2, height/2);
  rotateY(radians(45));
  fill(255);
  rect(0, 0, w, h);
  
  PVector p1 = new PVector(modelX(0, 0, 0), modelY(0, 0, 0), modelZ(0, 0, 0));
  PVector p2 = new PVector(modelX(w, 0, 0), modelY(w, 0, 0), modelZ(w, 0, 0));
  PVector p3 = new PVector(modelX(w, h, 0), modelY(w, h, 0), modelZ(w, h, 0));
  PVector p4 = new PVector(modelX(0, h, 0), modelY(0, h, 0), modelZ(0, h, 0));
  
  PVector mouse = new PVector(modelX(mouseX-width/2, mouseY-height/2, 0), 
                              modelY(mouseX-width/2, mouseY-height/2, 0), 
                              modelZ(mouseX-width/2, mouseY-height/2, 0));
  
  PMatrix3D m = (PMatrix3D) getMatrix();
  m.invert();
  
  popMatrix();
  
  // -------------------------------------------------------------
  
  PVector c1 = m.mult(p1, null);
  PVector c2 = m.mult(p2, null);
  PVector c3 = m.mult(p3, null);
  PVector c4 = m.mult(p4, null);
  
  PVector cm = m.mult(mouse, null);
  
  pushMatrix();
  beginShape();
  translate(width*0.4, 0);
  noFill();
  stroke(255);
  vertex(c1.x, c1.y);
  vertex(c2.x, c2.y);
  vertex(c3.x, c3.y);
  vertex(c4.x, c4.y);
  endShape(CLOSE);
  
  ellipse(cm.x, cm.y, 10, 10);
  popMatrix();
  
  
}
1 Like

This is not a complete answer but collisions with rotated cubes can be quite difficult and require quite a bit of knowledge about trigonometry. I’d start by drawing sketches of cubes only rotating in one axis and try to find easier solutions based on that. One method I came up with was checking if the point collides with a 2D polygon made from the 4 top or bottom points, then checking to see if the collision is inside of the y range of that cube

rotated_cube_test

Yeah in 2d I cn do that using the inverse matrix.

Did you get it working?

It is most unlikely that you can do that because you can only get 2 coordinates with the mouse and there is no way to get the third coordinate to specify a 3D position. The best you can get is a 3D vector of the direction you are looking and use ray-tracing to see if it intersects the quad.