【发布时间】:2015-12-29 01:49:55
【问题描述】:
我有一个游戏的一部分,当光标经过某些 div 时,它应该“减速”。我正在使用一个可以检测与 div 冲突的函数。这在光标遇到第一个 div 时可以正常工作,但在第二个 div 上根本不起作用。
Check out this jsFiddle 以便更好地了解我在说什么。将光标移到左侧的第一个白色块 (class='thing') 上,它就会减速。将光标移到另一个块上(也是class='thing'),什么也没有发生。我需要这个碰撞函数来处理class='thing' 的所有div。
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);
})();
【问题讨论】:
-
$thing 是一个集合
-
避免将
setInterval用于动画,因为它会导致(实际上,在您的 JSFiddle 中导致)滞后。使用window.requestAnimationFrame。 -
@YeldarKurmangaliyev 感谢您的链接!我会调查的。
标签: javascript jquery html css function