我有游戏的一部分,当游标通过某些div时,光标应该“减速”.我使用的功能可以检测到与div的碰撞.当光标符合第一个div时,这样可以正常工作,但是在第二个div上它根本不工作.
Check out this jsFiddle更好地了解我在说什么.将光标移到左边的第一个白色块(class =’thing’)上,并将其放慢.将光标传递到另一个块(也是class =’thing’),没有任何反应.我需要这个碰撞函数来处理所有div,其中class =’thing’.
HTML
<div id='cursor'> </div> <div class='thing' style='width:70px; height:70px; background: #fff; position: absolute; bottom: 350px; right: 800px; z-index: -1;'> </div> <div class='thing' style='width:70px; height:70px; background: #fff; position: absolute; bottom: 200px; right: 400px; z-index: -1;'> </div>
JS
(function collide(){ var newInt = setInterval(function() { function collision($cursor,$thing) { var x1 = $cursor.offset().left; var y1 = $cursor.offset().top; var h1 = $cursor.outerHeight(true); var w1 = $cursor.outerWidth(true); var b1 = y1 + h1; var r1 = x1 + w1; var x2 = $thing.offset().left; var y2 = $thing.offset().top; var h2 = $thing.outerHeight(true); var w2 = $thing.outerWidth(true); var b2 = y2 + h2; var r2 = x2 + w2; // change 12 to alter damping higher is slower var varies = 12; if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2){ } else { varies = 200; console.log(varies); } $xp += (($mouseX - $xp)/varies); $yp += (($mouseY - $yp)/varies); $("#cursor").css({left:$xp +'px',top:$yp +'px'}); } $(collision($('#cursor'),$('.thing'))); //$('.result').text(collision($('#cursor'),$('.thing'))); },20); })();