Div overlapping and collision position

Kiwimoisi

I am trying to see when my two divs are going to overlap and touch each other. The two yellow divs on this example.

Why is it that the collision returns true at a stage when the divs aren't even overlapping or touching each other ?

http://jsfiddle.net/HWfMt/156/

    var degree = 0;
var degreeSmall = 0;
var timer=30;
var $spin = $(".gear");
var $spinSmall = $(".gear-small");
var to;
var toSmall;

function collision($div1, $div2) {
  var x1 = $div1.offset().left;
  var y1 = $div1.offset().top;
  var h1 = $div1.outerHeight(true);
  var w1 = $div1.outerWidth(true);
  var b1 = y1 + h1;
  var r1 = x1 + w1;
  var x2 = $div2.offset().left;
  var y2 = $div2.offset().top;
  var h2 = $div2.outerHeight(true);
  var w2 = $div2.outerWidth(true);
  var b2 = y2 + h2;
  var r2 = x2 + w2;

  if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2) return false;
  return true;
}

$( document ).ready(function() {

    rotate();
});


function rotate() {
    degree++;
    $spin.css({ 'WebkitTransform': 'rotate(' + degree + 'deg)'});  
    $spin.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});

    to = setTimeout(function() {
        rotate();
    }, timer);

    $('#result').text(collision($('.gear .inner-gear.yellow'), $('.gear-small .inner-gear.yellow')));

}

Thanks

user

The intersection test code is right for axis-aligned bounding boxes. If that's what you were trying to check, then the problem you have here is that the box coordinates that you are checking are wrong. I won't fix this for you, but I'll show you how to debug this easily:

Add a semitransparent overlay:

<div id="bb" style="background:rgba(0,0,0,0.5); position:absolute;"></div>

And see what you are comparing:

$('#bb').offset({left:x1,top:y1}).width(w1).height(y1);

Updated JSFiddle.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related