jQuery/JavaScript collision detection

前端 未结 7 2172
情话喂你
情话喂你 2020-11-22 04:49

How to detect if two

elements have collided?

The two divs are simple coloured boxes travelling perpendicular to each other, so no complicate

7条回答
  •  别那么骄傲
    2020-11-22 05:34

    I ran into this generalized issue myself, so (full disclosure) I made a plugin for it. For simple collision queries about static objects, try this:

    http://sourceforge.net/projects/jquerycollision/

    Which allows you to get a list of overlapping collision boxes (or none if there's no collision):

    hits = $("#collider").collision(".obstacles");

    Or to get a collision event during "dragging", use this:

    http://sourceforge.net/apps/mediawiki/jquidragcollide/?source=navbar#collision

    Which gives you a "collision" event to connect to. (Or a "protrusion" event, to see if a div escapes another div that currently contains it.)

    $(draggable).bind( 
       "collision",
       function(event,ui) {
          ...
       }
    );
    

    If you are checking collisions during motion other than dragging, just call the original repeatedly, it's pretty quick. Note: the dragging one doesn't play nicely with resizing.

提交回复
热议问题