Canvas Game Timer

前端 未结 2 1453
情歌与酒
情歌与酒 2021-01-22 10:43

I\'m making a HTML5 Canvas Game with a rectangle that moves around the canvas. The objective is to dodge multiple Balls moving across the canvas for as long as possible. But i\'

2条回答
  •  时光取名叫无心
    2021-01-22 11:09

    Here’s how to integrate a timer into your game:

    Set the startingTime just before you start the game ticker:

    /* Do the function, call every 20 milliseconds*/
    startTime=new Date();
    

    Draw the elapsed time whenever playGame is called:

    /* MAIN GAME */
    function playGame()
    {
        g.clearRect(0, 0, canvas.width, canvas.height);  //Clear canvas at start.
        player.draw();
         for (var i = 0; i < 8; i++)
        {
            ball[i].move();
            ball[i].draw();
        }
    
        // draw the score
        drawElapsedTime();
    }
    

    And finally, draw the final score when the game is over:

    drawFinalScore();
    alert("GAME OVER");
    

    Also, I noticed you left the game ticker running even after the game ended. Here’s how to turn off the ticker:

    // turn on the ticker and get a reference to the object
    var theInterval=setInterval(playGame, 20);
    
    // turn off the ticker
    clearInterval(theInterval);
    

    And…check out the new requestAnimationFrame ticker. It’s much more efficient and resource friendly than the older setInterval ticker. Here’s a link for requestAnimationFrame: http://paulirish.com/2011/requestanimationframe-for-smart-animating/

    Here is code and a Fiddle: http://jsfiddle.net/m1erickson/8qKht/

    
    
    
    
    
    
    
    
    
        

    A V O I D

提交回复
热议问题