JavaScript Canvas精灵动画速度

时间:2013-04-29 21:19:15

标签: javascript html5 canvas

我的画布动画有问题。我正在使用this tutorial。 这很简单,但现在我想制作60 fps的动画。我试过setInterval(Update, 1000/60),当然它正在运行,但现在精灵有问题。它的动画太快了。有没有办法制作60fps并减慢角色精灵动画(看起来更自然)?

对不起,我没有实例,但是为精灵创建一个没有ftp的东西有点难。

代码:

var canvas;
var ctx;
var dx = 10;
var x = 30;
var y = 0;
var WIDTH = 1000;
var HEIGHT = 340;
var tile1 = new Image ();
var posicao = 0;
var NUM_POSICOES = 3;

    function KeyDown(e){
        switch (e.keyCode) {
            case 39: 
                if (x + dx < WIDTH){
                    x += dx;
                    posicao++;
                    if(posicao == NUM_POSICOES)
                        posicao = 1;
                }
                break;   
        case 37:
            if (x + dx < WIDTH){
                    x -= dx;
                    posicao++;
                    if(posicao == NUM_POSICOES)
                        posicao = 1;
                }

        }
    }
    function KeyUp(e){
        posicao = 0;
    }
    function Draw() {   
        tile1.src = posicao+".png";
        ctx.drawImage(tile1, x, y);
    }
    function LimparTela() {
        ctx.fillStyle = "rgb(233,233,233)";   
        ctx.beginPath();
        ctx.rect(0, 0, WIDTH, HEIGHT);
        ctx.closePath();
        ctx.fill();   
    }
    function Update() {
        LimparTela();   
        Draw();
    }
    function Start() {
        canvas = document.getElementById("canvas");
        ctx = canvas.getContext("2d");
        return setInterval(Update, 1000/60);
    }
        window.addEventListener('keydown', KeyDown);
        window.addEventListener('keyup', KeyUp);
Start();

3 个答案:

答案 0 :(得分:0)

只是一个想法,一个简单的修复,你可以尝试添加额外的帧到spritesheet?这也将改善你的动画,而不用担心破坏别的东西:)

答案 1 :(得分:0)

你可以&#34;油门&#34; Update()执行次数较少。

var counter=5;

function Update() {
    if(--counter>0){ return; };
    LimparTela();   
    Draw();
    counter=5;
}

如果用户按下某个键,您可以通过将计数器设置为0来强制动画。

function KeyDown(e){
    switch (e.keyCode) {
        case 39: 
            if (x + dx < WIDTH){
                x += dx;
                posicao++;
                if(posicao == NUM_POSICOES)
                    posicao = 1;
            }
            // zero the counter to force the animation now
            counter=0;
            break;   
    case 37:
        if (x + dx < WIDTH){
                x -= dx;
                posicao++;
                if(posicao == NUM_POSICOES)
                    posicao = 1;
            }
            // zero the counter to force the animation now
        counter=0;
    }
}

答案 2 :(得分:0)

无论何时移动精灵,都应该将移动的像素数除以每秒的帧数。例如,如果您想以60fps每秒移动dx像素,请将var fps = 60;定义为全局变量,并在移动时执行x += dx/fps;。以前的帧速率是多少? 30fps还是什么?无论它是什么,如果你希望它以60fps的速度和以前相同的速度,通过将你之前的dx乘以fps,使你的dx等于每秒行进的像素数。因此,如果它以30fps的速度以每帧10px的速度移动,请制作var dx = 300;

相关问题