首页 > 解决方案 > 在每个确认的游戏中,Square 跌得更快

问题描述

我在画布上有正方形,当用户单击画布时它会上升。否则会掉下来。当正方形触地时,会出现游戏结束警报并期望用户采取行动。如果用户确认,游戏会重新开始,但这里的问题是,开始下降当用户想再次播放时总是更快。下面是我的 JS 代码。我怎样才能让它的下降速度与第一次一样恒定?

var c = document.getElementById("gameCanvas");
var ctx = c.getContext("2d");
var recWidth,recHeight,xPos,yPos;
var gameStarted=false;

boxInitializer();

function startGame(){
     this.gameStarted=true;
     init();
}

function boxInitializer(){
    this.recWidth = 100;
    this.recHeight = 100;
    this.xPos = (document.getElementById("gameCanvas").width/2) - (recWidth/2);
    this.yPos = (document.getElementById("gameCanvas").height/2) - (recHeight/2);
    ctx.fillRect(xPos,yPos,recWidth,recHeight);
    console.log('XPos:'+xPos+'YPos:'+yPos);
}

function init(){
    if(gameStarted){
        const myVar=250;
        this.c.addEventListener('click', Up,false);
        setInterval(Down,myVar);
        console.log(myVar);
        setInterval(obstacleGenerator,2000); 
        function obstacleGenerator(){

            console.log("Obstacle generated");
        }
        function drawSquare(){
            this.ctx.fillRect(this.xPos,this.yPos,this.recWidth,this.recHeight);
        }
        function clearSquare(){
            this.ctx.clearRect(this.xPos,this.yPos,this.recWidth,this.recHeight);
        }
        function Up()
        {
           clearSquare();
            yPos-=40;
            drawSquare();
        } 
        function Down()
        {
            clearSquare();
            this.yPos+=30;
            console.log(yPos);
            drawSquare();
            if(this.yPos>=830){
                this.gameStarted=false;
                GameOver();
            }
        }
        function GameOver(){
            if (confirm("GAME OVER!")) {
            clearSquare();
            boxInitializer();
            startGame();
            } else {

            }
        }    

    }

}

JS 小提琴https ://jsfiddle.net/qmz3186h/

标签: javascripthtml

解决方案


在这里你需要清除你的gameStartedDown 间隔gameOver

你可以有一个变量来保持间隔,并在游戏结束功能中清除相同

var interval; // initialize at top

interval = setInterval(Down,myVar); // replace with this in `if(gameStarted)` loop

clearInterval(interval ) // clear interval on confirm("GAME OVER!")

推荐阅读