繁体   English   中英

JavaScript Canvas Sprite动画速度

[英]JavaScript Canvas sprite animation speed

我的画布动画有问题。 我正在使用本教程 这很简单,但是现在我想以60 fps的速度制作动画。 我尝试了setInterval(Update, 1000/60) ,它当然可以工作,但是现在精灵有问题。 它的动画太快了。 有什么方法可以使60fps并减慢角色精灵动画的速度(看起来更自然)?

抱歉,我没有实时的示例,但是要创建一个没有ftp的sprite会有点困难。

编码:

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();

只是一个想法,一个简单的修补程序,您可以尝试在Spritesheet中添加额外的帧? 这也将改善您的动画效果,而不必担心会破坏其他东西:)

您可以“限制” 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;
    }
}

每当移动精灵时,都应将移动的像素数除以每秒的帧数。 例如,如果要以60fps的速度每秒移动dx像素,请定义var fps = 60; 作为全局变量并执行x += dx/fps; 当你移动他时。 以前的帧速率是多少? 30fps或什么? 无论是什么,如果您希望它以60fps的速度与以前一样,请通过将以前的dx乘以fps,使dx等于每秒移动的像素数。 因此,如果它以30fps的速度每帧移动10px,则使var dx = 300;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM