我正在制作一个简单的网络游戏,其中可以使用箭头键在页面上移动一个 div,目的是使其与另一个 div 发生碰撞。然后第二个 div 将随机放置在页面的其他位置。我的问题是,如何更改为以下代码以重新定位第二个 div apon 碰撞?
我有代码在单击 div 时执行此操作
$('#test').click(function() {
var docHeight = $(document).height(),
docWidth = $(document).width(),
$div = $('#test'),
divWidth = $div.width(),
divHeight = $div.height(),
heightMax = docHeight - divHeight,
widthMax = docWidth - divWidth;
$div.css({
left: Math.floor( Math.random() * widthMax ),
top: Math.floor( Math.random() * heightMax )
});
});
我希望在 jquery、js 或 angular 中执行此操作。感谢您的帮助。
最佳答案
也许类似于 https://api.jquery.com/offset/ :
$('moving_div').click(function(){ // or the action you make the div move
if ( $('#moving').offset().left == $('#target').offset().left && $('#moving').offset().top == $('#target').offset().top ) {
$('target_div').css({
left: Math.floor( Math.random() * widthMax ),
top: Math.floor( Math.random() * heightMax )
});
}
});
关于javascript - 当动画 div 跨越坐标时随机重新放置一个 div 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29688433/