Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
  </head>
  <body>
    <div id="box1" class="box box1">
      box1
    </div>
    <div id="box2" class="box box2">
      box2
    </div>
    <div id="notes" />
  </body>
</html>
 
.box {
    font-size: 8pt;
    opacity: 0.5;
    text-align: center;
    position: absolute;
}
.box1 {
    background-color: green;
    left: 10px; top: 60px;
    width: 150px; height: 120px;
}
.box2 {
    background-color: green;
    left: 60px; top: 190px;
    width: 170px; height: 140px;
}
.collision {
    background-color: red!important;
}
 
function detectCollisions(event, ui) {
  var $box1 = $("#box1");
  var $box2 = $("#box2");
  var r1 = elementRect($box1);
  var r2 = elementRect($box2);
  $box1.text("box1: " + rectAsText(r1));
  $box2.text("box2: " + rectAsText(r2));
    
  var minkowski = {
    left:   r1.left - r2.right,
    top:    r2.top - r1.bottom,
    width:  r1.width + r2.width,
    height: r1.height + r2.height,
    right:  r1.right - r2.left,
    bottom: r2.bottom - r1.top
  };
  var collision =
    minkowski.left <= 0 &&
    minkowski.right >= 0 &&
    minkowski.top <= 0 &&
    minkowski.bottom >= 0;
  $boxes = $("#box1,#box2");
  if (collision) {
    $boxes.addClass("collision");
  }
  else {
    $boxes.removeClass("collision");
  }
     
  $("#notes").html(
    "collision: " + collision +
    "<br/>minkowski: " +
    rectAsText(minkowski));
}
function elementRect($element) {
  var rect = {
    left:   $element.position().left,
    top:    $element.position().top,
    width:  $element.width(),
    height: $element.height()
  };
  rect.right  = rect.left + rect.width;
  rect.bottom = rect.top + rect.height;
  return rect;
}
function rectAsText(r) {
  return r.left + ", " +
         r.top + ", " +
         r.right + ", " +
         r.bottom;
}
$(function() {
  detectCollisions();
  $("#box1").draggable({
    drag: detectCollisions
  });
  
  $("#box2").draggable({
    drag: detectCollisions
  });
});
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers