4

I'm making a game in javascript and I cant find anything like a function that will take 2 bounding box objects and return true if they intersect. all the examples I've found seem far too complex for my little game and most are language specific :/

//my box object
function bounding_box (x, y, width, height, rotation) {
  var box = {};
  box.x = x;
  box.y = y;
  box.w = width
  box.h = height;
  box.r = rotation; //degrees from origin - all objects in the game have the same rotation origin
  return box;
}

function boxes_collide (a, b) {
  //if collision return true
  //else return false

  //my box collision function at the moment
  //doesn't work with rotation
  return !(
      ((a.y + a.h) < (b.y)) ||
      (a.y > (b.z + b.h)) ||
      ((a.x + a.w) < b.x) ||
      (a.x > (b.x + b.h))
  );
}

//create boxes
var boxa = bounding_box(0, 0, 5, 3, 45);
var boxb = bounding_box(1, 3, 4, 2, 90);

//test for collision
if (boxes_collide (boxa, boxb)) {
  alert('collision');
}

I've been stuck for hours on this little problem, any help would be appreciated! :)

nevernew
  • 650
  • 10
  • 23
  • 2
    This might help http://wiki.processing.org/w/Rect-Rect_intersection – elclanrs Dec 18 '12 at 03:32
  • i have pretty much exactly that function already, but as my boxes rotate, its not very accurate :/ – nevernew Dec 18 '12 at 03:39
  • 3
    You should to use Separating Axis Test for Oriented Bounding Boxes(rotated rects). I wrote a little SAT visualization a while back to help me understand OBBs and SAT. Here is the JSBin, tell me if this is what you need: http://jsbin.com/esubuw/4 – Rikonator Dec 19 '12 at 11:23
  • Hope my [answer](https://stackoverflow.com/a/41513341/2401386) helps you as well. – Blauharley Dec 19 '17 at 17:45

1 Answers1

-1

Parameter b has no property called z.

Bob Lyon
  • 44
  • 3