我在一个简单的(或者我认为的)Pong游戏中使用jQuery Collision。没有人工智能或在线互动,只有两个拨片和一个或两个现实生活中的球员可以控制的球。
当试图给球制作动画并检查它是否与任何东西发生碰撞时,我的表现很短暂。我已经阅读了关于SourceForge的文档(参见上面的链接),但我仍然有点迷失在如何实际检查对撞机是否实际碰到任何东西。在我看来,文档可以使用一些例子。
我目前拥有的JavaScript代码:
$(document).ready(function()
{
var ball = $("#ball");
var topPaddle = $("topPaddle");
var bottomPaddle = $("bottomPaddle");
var topPaddleHits = $("#ball").collision("#topPaddle", { mode: "collision", obstacleData: "topOData" });
var bottomPaddleHits = $("#ball").collision("#bottomPaddle", { mode: "collision", obstacleData: "bottomOData" });
var anim = setInterval(function()
{
ball.css({ "left": "+=5", "top": "+=5" });
if (bottomPaddleHits.data("bottomOData") == bottomPaddle)
{
anim = clearInterval(anim);
alert("Bottom paddle hit!");
}
}, 50);
});
我也试过if (bottomPaddleHits == 1)
,但这也不好。
顶部/底部拨片和球的CSS,如果重要的话:
#ball
{
width: 10px;
height: 10px;
position: absolute;
background: #FFF;
top: 200px;
left: 100px;
}
#topPaddle
{
position: absolute;
width: 300px;
height: 10px;
background: lime;
top: 100px;
left: 50px;
}
#bottomPaddle
{
position: absolute;
width: 300px;
height: 10px;
background: lime;
bottom: 100px;
left: 50px;
}
我只是不确定如何检查某些东西是否真的被击中。
答案 0 :(得分:1)
那个碰撞插件似乎有非常糟糕的文档,我认为使用像jQuery UI这样有更好的文档和支持的东西会容易得多。以下是我放在一起检测碰撞的快速内容。
<div class="drop">
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
<div class="drag"></div>
</div>
$('.drop').droppable({
tolerance: 'fit'
});
$('.drag').draggable({
revert: 'invalid',
stop: function(){
$(this).draggable('option','revert','invalid');
}
});
$('.drag').droppable({
greedy: true,
tolerance: 'touch',
drop: function(event,ui){
//ui.draggable.draggable('option','revert',true);
alert('touched');
}
});
并且放置警报的位置可以使用ui参数来获取碰撞发生位置和偏移量。