Monday, February 15, 2016

Switching to Frame Based Tweens in Phaser

This weekend I was doing some more work on my 8-bit style Phaser platformer. I added another enemy (a rabbit) and made some changes which will make it easier to add even more enemies. But during my extensive play-testing I noticed that I was having a lot of trouble with my moving platforms. Both the ridable clouds and the collapsing platforms seemed to move away from the frog, and then the frog's motion became very choppy as it was repositioned.

Frogs can now battle rabbits in the dark forest.

After playing around with some things, I determined that the issue was caused by a slightly lagging frame rate. I had a bunch of other things running on my laptop and the game wasn't running quite as quickly as it was before. The physics engine, which controlled the frog's movements, was making updates based on how much time was elapsing between frames. The movement of the platforms was being handled by Tweens, which by default calculate their movement in constant time. When the frame rate dips below 60 per second, the two get out of sync. Normally this would not be that noticeable but in the situation where the two objects are tied together, it caused some issues.

To resolve these problems, I switched the Tweens into "frame based" mode. This is as easy as setting a boolean flag once in the create function.

function create() {
        
    // ... other stuff ...
     
    this.tweens.frameBased = true;

    // ... other stuff ...

}

When running in frame based mode, the Tweens will use the physics engine's update timer. When I switched to this mode, the frog and the platforms remain in sync much better when the frame rate dips a little. I did have to adjust the duration values in most of my Tweens, since in frame based mode the duration should represent number of frames instead of number of milliseconds. But it was a simple adjustment.

Remember, you can view the complete source code for the game on GitHub, and play the current version at this link: http://amphibian.com/eight-bit.

Before you go, be sure to read today's Amphibian.com comic - and give me a vote on TopWebcomics.com if you have an extra second!

Amphibian.com comic for 15 February 2016