简体   繁体   中英

setInterval inside the gameloop, not working as intended

I'm making a little canvas game but I cannot get the setInterval to work well inside of the gameloop.

With this code the interval runs once and then the gameloop seems to take over and runs all the time.

<html>
<head>

<script type="text/javascript">
    //Gameloop
    function gameLoop(){
        update();
        draw();
        requestAnimationFrame(gameLoop);
    }

    var x=50;
    var y=50;

    // update values
    function update(){
        x++;
        //timer to increase speed once every 2 seconds
        function timer(){
        x = x +5;
        }
        var interval = setInterval(timer, 2000);
    }

    //Draw onto canvas
    function draw(){
        var canvas = document.getElementById('canvas');
        if (canvas.getContext) {
            var ctx = canvas.getContext('2d');
        }
        ctx.clearRect(0,0,800,800);
        ctx.beginPath();
        ctx.rect(x,y,25,25);
        ctx.fill();
    }
</script>
</head>

<body onload=gameLoop()>
<canvas id="canvas" width="800" height="800"></canvas>
</body>
</html>

Each gameloop was firing another interval. Try using frame times for interval instead. Also get the canvas and context once as a global for increased frames per second.

 var elFps = document.getElementById("fps"); var fps = 0; var fpsInterval = setInterval(function(){ elFps.innerHTML = 'fps='+fps; fps = 0; }, 1000); var speed = 1; var gameStart = Date.now(); var speedUpTime = gameStart + 2000; var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); //Gameloop function gameLoop(){ var frameTime = Date.now(); if (frameTime >= speedUpTime) { speed+=1; speedUpTime += 2000; } fps++; update(); draw(); requestAnimationFrame(gameLoop); // This is your looper } var x=50; var y=50; // update values function update(){ x+=speed; } //Draw onto canvas function draw(){ ctx.clearRect(0,0,800,800); ctx.beginPath(); ctx.rect(x,y,25,25); ctx.fill(); } gameLoop(); 
 <div id="fps"> - </div> <canvas id="canvas" width="800" height="800"></canvas> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM