Frage

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...

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top