这是一个错误吗? (JavaScript条件)
我有一些代码用于游戏的一部分,其中一个绝对定位的div( id = 'cursor'
)跟随你的鼠标光标。 当cursor
div进入另一个div( class = 'thing'
)(这些是jsfiddles中的白框)时, cursor
速度会发生变化。
在这个JSfiddle中,你会发现它完美无缺。 当cursor
点击时, cursor
加速。 这是用于更改速度的条件( newSpeed
决定cursor
的速度):
if (b1 b2 || r1 r2){ newSpeed = 200; changeCursorSpeed(); } else { newSpeed = 12; changeCursorSpeed(); console.log('hit'); }
我遇到的问题是当我在条件中切换newSpeed
的值时:
if (b1 b2 || r1 r2){ newSpeed = 12; changeCursorSpeed(); } else { newSpeed = 200; changeCursorSpeed(); console.log('hit'); }
这是JSFiddle。 这会导致碰撞不会在条件的else
部分更改newSpeed
。 但是,使用console.log('hit')
,您可以清楚地看到检测到碰撞。
从逻辑上讲,这似乎没有意义。 我想听听别人对此的意见以及可能的解决方案。 谢谢你的帮助。
这是碰撞检测的完整代码。 JSfiddles有一个更完整的程序代码。
var newSpeed; 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; $thing.each(function(i){ var x2 = $(this).offset().left; var y2 = $(this).offset().top; var h2 = $(this).outerHeight(true); var w2 = $(this).outerWidth(true); var b2 = y2 + h2; var r2 = x2 + w2; if (b1 b2 || r1 r2){ newSpeed = 12; changeCursorSpeed(); } else { newSpeed = 200; changeCursorSpeed(); console.log('hit'); } }); function changeCursorSpeed(){ $xp += (($mouseX - $xp)/newSpeed); $yp += (($mouseY - $yp)/newSpeed); $("#cursor").css({left:$xp +'px', top:$yp +'px'}); } } $(collision($('#cursor'), $('.thing'))); }, 20);