0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. It works. Added this if (lastTime == 0) lastTime = Date.now();to the main loop and it's smooth.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.