0

I tried to make some simply game using requestAnimFrame but animation doesn't work and I don't know why. Maybe some one can help? Here is the code:

// requestAnimationFrame() shim by Paul Irish
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
window.requestAnimFrame = (function(){
    return  window.requestAnimationFrame       || 
            window.webkitRequestAnimationFrame || 
            window.mozRequestAnimationFrame    || 
            window.oRequestAnimationFrame      || 
            window.msRequestAnimationFrame     || 
            function(/* function */ callback, /* DOMElement */ element){
                window.setTimeout(callback, 1000 / 60);
            };
})();

//Create canvas
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 640;
canvas.height = 480;
document.body.appendChild(canvas);

// The main game loop
var lastTime;

function main() {

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

    draw();
    update(dt);

    lastTime = now;
    requestAnimFrame(main);
}

main();

function ball(){
    this.radius = 5;
    this.x = 300;
    this.y = 50;
    this.vx = 200;
    this.vy = 200;
    this.ax = 0;
    this.ay = 0;
    this.color = "red";
    this.draw = function(){
        ctx.beginPath();
        ctx.fillStyle = this.color;
        ctx.arc( this.x, this.y, this.radius, 0, 2 * Math.PI );
        ctx.fill();
    };
}

function draw() {
    newBall = new ball();
    newBall.draw(); 
}

function update(dt) {
    newBall = new ball();
    newBall.x += newBall.vx * dt;
}

In update(dt) function ball dosen't move and I don't know why...

1
  • 1
    one thing is that dt is almost always the same. The other thing is that you're creating a new ball each time. is that the intent, or are you just trying to move the one?
    – kalley
    Jul 13, 2013 at 6:24

1 Answer 1

0

There are several errors in your code:

  1. You're initializing variables outside of a function, always use an initializer (immediately invoked function) for that.
  2. As mentioned by kalley you are creating a new ball at the starting position for every draw instead of using a global object.
  3. Even if your ball would draw correctly it would be outside the drawing area within the next frame because Date.now() is measured in seconds (use .getMilliseconds()).
  4. Lastly the ball stays at the same position because the canvas isn't cleaned up after each draw.

what you're looking for:

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    theBall.draw();
}

There are several other things but this fiddle should do for now.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.