PixiJS v4 Limiting Frame Rate

2k views Asked by At

Using a spritesheet, I'm trying to figure out the best way to animate through all the frames smoothly and consistently, though I need to lower the FPS from 60 to 30.

Trying to use AnimatedSprite always defaults to 60 fps, which makes my animation flow too fast.

var frames = [];

for (var i = 0; i < maxFrames; i++){
    frames.push(PIXI.Texture.fromImage("spriteFrame_"+ i));
}

//// How to do it via AnimatedSprite
var s = new PIXI.extras.AnimatedSprite(frames);
s.play();
Stage.addChild(s);

My current way of doing it sets the sprite's texture manually, and hackily halves the frame rate

// in bonusSymbol.js
var curFrameNumber = 0;

function nextFrame(){
   curFrameNumber ++;

   if(curFrameNumber >= frames.length){
      curFrameNumber = 0;
   }

   sprite.texture = frames[curFrameNumber];
}

// in game.js
function gameLoop() {
    //Loop this function at 60 frames per second
    requestAnimationFrame(gameLoop);

    // Force to only update on half frames (30fps)
    if(frameCounter == 1){
        frameCounter = 0;
        return;
    }
    frameCounter++;


    bonusSym.NextFrame();
    Scene.Render()
};

Is there any alternative or better way of doing this?

1

There are 1 answers

1
themoonrat On BEST ANSWER

There is a property for AnimatedSprite called animationSpeed.

var frames = [];

for (var i = 0; i < maxFrames; i++){
    frames.push(PIXI.Texture.fromImage("spriteFrame_"+ i));
}

//// How to do it via AnimatedSprite
var s = new PIXI.extras.AnimatedSprite(frames);
s.animationSpeed = 0.5;
s.play();
Stage.addChild(s);

Alternatively, instead of just an array of textures to give to the AnimatedSprite, you can pass through an array of FrameObject, which give both the texture and how long it should be displayed for in ms.

var frames = [];

for (var i = 0; i < maxFrames; i++){
    frame = {
        texture: PIXI.Texture.fromImage("spriteFrame_"+ i),
        time: 33
    };
    frames.push(frame);
}

//// How to do it via AnimatedSprite
var s = new PIXI.extras.AnimatedSprite(frames);
s.play();
Stage.addChild(s);