原生js实现Flappy Bird小游戏
编程学习 2021-07-04 15:50www.dzhlxh.cn编程入门
这篇文章主要为大家详细介绍了原生js实现Flappy Bird小游戏,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
这是一个特别简单的用原生js实现的一个小鸟游戏,比较简单,适合新手练习。
html结构
<div id="game"> <div id="bird"></div> </div>
css样式
#game { width: 800px; height: 600px; border: 1px solid #000; background: url(images/sky.png); overflow: hidden; position: relative; } #game .pipeD { background: url(images/pipe1.png) top center; position: absolute; } #game .pipeU { background: url(images/pipe2.png) bottom center; position: absolute; } #bird { width: 34px; height: 25px; /*border-radius: 10px;*/ /*background-color: red;*/ position: absolute; top: 100px; left: 100px; background: url(images/birds.png) -8px -10px no-repeat; }
狼蚁网站SEO优化就是原生js代码了,这个小案例还运用了自己前期封装的一个小的动画方法
function animate(obj, json, fn) { clearInterval(obj.timer); obj.timer = setInterval(function () { var flag = true; for (var k in json) { if (k === "opacity") { var leader = getStyle(obj, k) * 100; var target = json[k] * 100; var step = (target - leader) / 10; step = step > 0 ? Math.ceil(step) : Math.floor(step); leader = leader + step; obj.style[k] = leader / 100; } else if (k === "zIndex") { obj.style.zIndex = json[k]; } else { var leader = parseInt(getStyle(obj, k)) || 0; var target = json[k]; var step = (target - leader) / 10; step = step > 0 ? Math.ceil(step) : Math.floor(step); leader = leader + step; obj.style[k] = leader + "px"; } if (leader !== target) { flag = false; } } if (flag) { clearInterval(obj.timer); if (fn) { fn(); } } }, 15); } function getStyle(obj, attr) { if (window.getComputedStyle) { return window.getComputedStyle(obj)[attr]; } else { return obj.currentStyle[attr]; } }
狼蚁网站SEO优化就是控制游戏的js代码了
var birdElement = document.getElementById("bird"); var game = document.getElementById("game"); var gameover = false; var g = 1; var i = 0; var timer=null; var bird = { x: birdElement.offsetLeft, y: birdElement.offsetTop, speedX: 5, speedY: 0, entity: birdElement }; var sky = { x: 0 }; //var timer=setInterval(function(){ // birdElement.style.backgroundPositionX=-52*i+"px"; // i++; // if(i===3){ // i=0; // } /