I\'m just developing a simple balloon game with two divs. The problem is that I\'m unable to trigger a function when the two divs touch each other.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You\'re looking for bounding box collision detection. If you want to raise an event, you have to repeatedly test, but it would be better just to run the function over all your game objects from your game loop. The sandbox is at http://jsfiddle.net/nGRwt/7/
function collision($div1, $div2) {
var x1 = $div1.offset().left;
var y1 = $div1.offset().top;
var h1 = $div1.outerHeight(true);
var w1 = $div1.outerWidth(true);
var b1 = y1 + h1;
var r1 = x1 + w1;
var x2 = $div2.offset().left;
var y2 = $div2.offset().top;
var h2 = $div2.outerHeight(true);
var w2 = $div2.outerWidth(true);
var b2 = y2 + h2;
var r2 = x2 + w2;
if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2) return false;
return true;
}
回答2:
You can try jquery-collision plus jquery-ui-draggable-collision. Full disclosure: I just wrote and released these on sourceforge.
The first allows this:
var hit_list = $(\"#collider\").collision(\".obstacle\");
which is the list of all \".obstacle\" that overlap \"#collider\".
The second allows:
$(\"#collider\").draggable( { obstacle: \".obstacle\" } );
Which gives you (among other things), a \"collision\" event to bind to:
$(\"#collider\").bind( \"collision\", function(event,ui){...} );
And you can even set:
$(\"#collider\").draggable( { obstacle: \".obstacle\", preventCollision: true } );
to prevent \"#collider\" from ever overlapping any \".obstacle\" while dragging.
Ta的文章
更多文章
0条评论
还没有人评论过~