2014-02-10 7 views
0

Я хочу обнаружить столкновение div, когда пользователь перетаскивает их мышью.Как обнаружить деление div в моем случае?

У меня есть что-то вроде

<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') 
         } 
        } 
      } 
    ) 

Я хочу, чтобы показать «хит объект», когда ДИВ тащится и ударил одного из изображения, но я не могу показаться, обнаружить столкновение. Может ли кто-нибудь мне помочь?

ответ

0

Вот несколько столкновений Обнаружение для перетаскиваемого объекта:

$('#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'); 
       } 
      } 
     }); 
    } 
}); 

И Demo

0

Прежде всего принять смотреть на:
Please recommend a JQuery plugin that handles collision detection for draggable elements

Но если вы хотите реализовать его самостоятельно, Вы должны искать Разделительные оси теорему:
Hyperplane separation theorem

Кроме того, вы можете использовать Javascript для jQuery по следующей ссылке:
Javascript game engine for jQuery

Смежные вопросы