0

I want to detect the div collision when user drag their mouse.

I have something like

<div id='drag-item'/>
    <img src='drag' />
</div>
 <img id='img1' src='img1.png'/>
 <img id='img2' src='img21.png'/>
 <img id='img3'  src='img3.png'/>
 <img id='img4'  src='img4.png'/>
 <img id='img5' src='img5.png'/>

  var objects = {
                   'img1': {'offset':330..other property...},
                   'img2': {'offset':-450,other property...},
                   'img3': {'offset' : 100,other property...} ,
                   'img4': {'offset' : 430,other property...},
                   'img5': {'offset' :-260,other property...}
                 }

JS

 $('#drag-item').draggable(
          drag: function(){
                    var p = $('#drag-item').offset();

                    for(var i in objects){
                        var t = $('#' + i).position()
                        var hei = $('#' + i).height() + p.top;

                        if(p.top >= t.top && p.top <= hei ){
                            console.log('hit the object')
                        }
                    }
           }
    )

I want to show 'hit the object' when the div is dragged and hit one of the image but I can't seem to detect the collision. Can anyone help me about it?

FlyingCat
  • 14,036
  • 36
  • 119
  • 198

2 Answers2

0

First of all take look at :
Please recommend a JQuery plugin that handles collision detection for draggable elements

But if you want to implement it by yourself , You have to look up Separating Axis Theorem:
Hyperplane separation theorem

Furthermore you can use Javascript game engine for jQuery by the following link :
Javascript game engine for jQuery

Community
  • 1
  • 1
JoeyBright
  • 343
  • 1
  • 3
  • 17
0

Here is some collision detection for a draggable object:

$('#drag-item').draggable({
    drag: function (event, ui) {
        var height = ui.helper.height();
        var divs = $('div.img').not($(this).children());

        var pos = ui.position;

        divs.each(function (index, value) {
            var t = $(this).position();
            var hei = $(this).height()

            if (t.top <= pos.top + height ) { // check for top collision
                if (pos.left <= t.left + $(this).width()) { // check for side collision
                    console.log('hit the object');
                }
            }
        });
    }
});

And a Demo

Bic
  • 3,141
  • 18
  • 29