難度解析 一、動畫效果 requestAnimationFrame 二、碰撞檢測 DIV以前是否重合css
<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); }