Loop forever and provide delta time

前端 未结 4 728
别跟我提以往
别跟我提以往 2021-01-03 07:01

I\'m writing an HTML5 Game Development Javascript framework and I want to provide the user the difference in time between the last tick and the current one.

         


        
相关标签:
4条回答
  • 2021-01-03 07:12

    This is what I use:

    var lastTick = performance.now()
    
    function tick(nowish) {
      var delta = nowish - lastTick
      lastTick = nowish
    
      update(delta)
      render(delta)
    
      window.requestAnimationFrame(lastTick)
    }
    
    window.requestAnimationFrame(lastTick)

    0 讨论(0)
  • 2021-01-03 07:19

    Just maintain a variable with the time of the last update, and calculate the elapsed time/delta time in tick itself.

    var lastUpdate = Date.now();
    var myInterval = setInterval(tick, 0);
    
    function tick() {
        var now = Date.now();
        var dt = now - lastUpdate;
        lastUpdate = now;
    
        update(dt);
        render(dt);
    }
    

    Here's a JSBin, though I don't think it's really needed... http://jsbin.com/okimam/10

    EDIT: I must point out that setInterval(tick, 0) does not necessarily mean that tick will be called immediately, with an interval of '0ms' between two calls. It depends on the browser.

    0 讨论(0)
  • 2021-01-03 07:20

    Are you over thinking it?

    var myInterval = window.setInterval(calculateForDeltaHere , 20);
    
    function calculateForDeltaHere () {
        /* Calculate delta time */
        dt = Math.random();
        tick(dt);
    }
    
    function tick() {  
      update();
      draw();
    }
    

    And when you want to stop the interval

    window.clearInterval(myInterval);
    
    0 讨论(0)
  • 2021-01-03 07:24

    Would like to give my two cents. Usually I use this deltatime method in my games:

    const perfectFrameTime = 1000 / 60;
    let deltaTime = 0;
    let lastTimestamp = 0;
    
    function start() {
        requestAnimationFrame(update);
    }
    
    function update(timestamp) {
        requestAnimationFrame(update);
        deltaTime = (timestamp - lastTimestamp) / perfectFrameTime;
        lastTimestamp = timestamp;
    
        // YOUR FRAME CODE HERE!
    
    }
    
    start();
    

    This ensure you will have perfect deltatime (as like Unity deltaTime) so you can scale your times to frame time.

    0 讨论(0)
提交回复
热议问题