由于某种原因,该游戏有时会停顿,并且管道会不时地重新出现。您能帮我找到原因吗?我认为
function update(timestamp) {
if (!start) start = timestamp;
var progress = timestamp - start;
if (progress > 1500) {pipes.push(new pipe()); progress = 0; start = timestamp;}
但我不确定。
<html>
<body>
<canvas width="500" height="800" id="canvas"></canvas>
<button onclick="do1"> </button>
<script>
var score = 0;
var start = null;
var last = 2000;
var pipes = [];
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var bird = new bird();
ctx.fillStyle="black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
var birdImg = new Image();
birdImg.src = "bird2.png";
window.addEventListener('keydown', function(){
if(event.keyCode == 32) {bird.up()}
});
//pipes.push(new pipe());
function update(timestamp) {
if (!start) start = timestamp;
var progress = timestamp - start;
if (progress > 1500) {pipes.push(new pipe()); progress = 0; start = timestamp;}
ctx.fillStyle="black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
bird.update();
bird.draw();
for(var i = 0; i < pipes.length; i++) {
pipes[i].update();
pipes[i].draw();
if(pipes[i].offscreen()) {pipes.splice(i,1)}
}
ctx.font = '20px georgia';
ctx.fillText(score, 30,30);
requestAnimationFrame(update);
}
update();
function bird() {
this.gravity = 0.6;
this.lift = -15;
this.x = 50;
this.y = canvas.height/2;
this.vy = 10;
this.draw = function() {
ctx.drawImage(birdImg, this.x, this.y, 70, 70);
}
this.update = function(){
this.vy += this.gravity;
this.vy *= 0.9;
this.y += this.vy;
if (this.y > 800-30) {
this.y = 800-30;
this.vy = 0;
}
}
this.up = function() {
this.vy += this.lift;
}
}
function pipe() {
this.top = Math.random()*canvas.height/2;
this.bottom = Math.random()*canvas.height/2;
this.x = canvas.width;
this.w = 40;
this.speed = 4;
this.alert = 0;
this.draw = function() {
ctx.fillStyle = "white";
ctx.fillRect(this.x, 0, this.w, this.top);
ctx.fillRect(this.x, canvas.height-this.bottom, this.w, this.bottom);
}
this.update = function() {
this.x -= this.speed;
if (this.x <= 50 && this.alert == 0) {
score+=100;
this.alert++
}
}
this.offscreen = function() {
return this.x < -this.w;
}
}
</script>
</body>
</html>
预先感谢