2D Collision Detection On Drag - Collidify.js

2D Collision Detection On Drag - Collidify.js
File Size: 6.96 KB
Views Total: 128
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

Collidify.js is a jQuery plugin for jQuery UI's draggable widget that can be used to determine whether two draggable objects collide and fire events accordingly.

How to use it:

1. The Collidify.js plugin required jQuery library and jQuery UI loaded in the page.

<link rel="stylesheet" href="/path/to/cdn/jquery-ui.min.css" />
<script src="/path/to/cdn/jquery.min.js"></script>
<script src="/path/to/cdn/jquery-ui.min.js"></script

2. Make an element draggable.

$(element).collidify(collisionOptions, jQueryUIdraggableOptions);

3. Detect if an element is draggable over (collide) another.

<div id="example">
  <div class="element-1">
    Element 1
  </div>
  <div class="element-2">
    Element 2
  </div>
</div>
$('.element-1').collidify({
  collides: [ $('.element-2')],
  onCollideEnter: function() {
    // do something
  },
  onCollideLeave: function() {
    // do something
  }
}, {
  containment: "#example"
})

4. Trigger the Collision events only if the element is completely dragged inside another element.

$('.element-1').collidify({
  collides: [ $('.element-2')],
  type: "inside",
  onCollideEnter: function() {
    // do something
  },
  onCollideLeave: function() {
    // do something
  }
}, {
  containment: "#example"
})

5. Add a custom border to the element when another element is dragged over it.

$('.element-1').collidify({
  border: [ $('.element-2')],
  borderStyle: "2px dashed blue",
  borderClass: ".border",
  onBorder: function() {
    // do something
  },
  onBorderRemove: function() {
    // do something
  },
}, {
  containment: "#example"
})

6. Restore the intial position after dropped.

$('.element-1').collidify({
  collides: [ $('.element-2')],
  revert: [ $('.element-2') ],
  onCollideEnter: function() {
    // do something
  },
  onCollideLeave: function() {
    // do something
  },
  onRevert: function() { 
    // do something
  },
}, {
  containment: "#example"
})

7. You can also pass the options as follows:

$('.element-1').collidify({
  border: [{
    element: $('.border'),
    type: "inside" 
  }],
  collides: [{
    element: $('.collide'),
    type: "enter"
  }],
  revert: [{
    element: $('.revert'),
    type: "inside"
  }]
}, {
  containment: "#example"
})

This awesome jQuery plugin is developed by Malmadork. For more Advanced Usages, please check the demo page or visit the official website.