I am implementing a simple animation using javascript in canvas.An image updates its position based on the time elapseddt between each frame. Here is the code

var lastTime=0;
var speed=100;

mySprite = function() {
  this.pos=[0,0];
}

function spritePosition(dt) {
  for (i=0; i < Stuff.sprite.length;i++) {
    Stuff.sprite[i].pos[0] += speed*dt;  
    }
}

function animate(){

  var canvas=document.getElementById('mycan');
  var context=canvas.getContext('2d');

  var now = Date.now();
  var dt = (now - lastTime) / 1000.0;

  //clear
  context.clearRect(0, 0, canvas.width, canvas.height);


  //update
  spritePosition(dt);
  updateSprite();

  //render
  background(canvas,context);
  draw(context);

  lastTime = now;

  //request new Frame
  requestAnimFrame(function() {
    animate();
  });
}

window.onload=function(){
  init();
  animate();
}

dt

values are in the range 0.3-0.5 But the line

Stuff.sprite[i].pos[0] += speed*dt;##

assigns position values as 136849325664.90016. Please help.

有帮助吗?

解决方案

You initialize lastTime to 0 - so the initial delta is veeeeery long (as of today almost 45 years!). You should make sure to catch the very first run (compare to 0? or initialize lastTime with Date.now()) and treat it separately, possibly setting dt to 0.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top