难度解析 1、动画效果 requestAnimationFrame 2、碰撞检测 DIV之前是否重合
<html>
<head>
<meta charset="utf-8" />
<style>
body{overflow-x:hidden;}
.ground{position:absolute;top:300px;width:10000px;height:10px;background:url(./ground.png) repeat-x}
.tree{width:100px;height:100px;background:green;position:absolute;left:1000px;top:200px;
}
</style>
<title></title>
</head>
<body>
<button onclick="stop();">stop</button>
<button onclick="jump();">jump</button>
<img src="./bird.png" id="bird" style="position:absolute;top:30px;left:200;border:1px red solid;" />
<div class="tree" id="tree"></div>
<div class="ground" id="ground"></div>
</body>
</html>
<script src="./jquery-1.11.0.min.js"></script>
<script src="./flppybird.js"></script>
var timer = requestAnimationFrame(fly)
var x = 0; //场景移动
//主函数
function fly() {
x--;
var top = $("#bird").offset().top;
top += 1;
$("#bird").css({
"top": top
});
$("#ground").css({
"left": x
});
var treeleft = $("#tree").offset().left;
treeleft--;
$("#tree").css({
"left": treeleft
});
//碰撞检测
if (checkCollection($("#bird"), $("#tree"))) {
stop();
alert("hit!");
} else {
timer = requestAnimationFrame(fly);
}
}
//检查是否碰撞
function checkCollection(bird, tree) {
var birdPosition = [];
birdPosition[0] = bird.offset().left;
birdPosition[1] = bird.offset().top + bird.height();
birdPosition[2] = bird.offset().left + bird.width();
birdPosition[3] = bird.offset().top + bird.height();
var treePosition = [];
treePosition[0] = tree.offset().left;
treePosition[1] = tree.offset().top;
treePosition[2] = tree.offset().left + tree.width();
treePosition[3] = tree.offset().top;
if (birdPosition[2] > treePosition[0] && birdPosition[0] < treePosition[2]) {
if (birdPosition[1] > treePosition[1]) {
return true;
}
}
return false;
}
//飞起来
function jump() {
var top = $("#bird").offset().top;
top -= 20;
$("#bird").css({
"top": top
});
}
//停止游戏
function stop() {
cancelAnimationFrame(timer);
}