Playing with Phaser 3 Tweens, Curves and cubic Bezier curves

When I updated my Down the Mountain prototype to Phaser 3 version, I did not use Bezier curve to tween player movement as I did in Phaser 2 version, because I couldn’t find an easy way to do it. Obviously, there could not be something I am not be able to do it with Phaser, so I started studying its new features like paths and native cubic Bezier support, and now I have the solution. Do you know what is a Bezier curve? A Bezier curve is a mathematically defined curve used in two-dimensional graphic applications. The curve is defined by four points: the initial position and the terminating position (which are called “anchors”) and two separate middle points (which are called “handles”). The shape of a Bezier curve can be altered by moving the handles. The mathematical method for drawing curves was created by Pierre Bézier in the late 1960’s for the manufacturing of automobiles at Renault. Look at the prototype I made:
Drag any of the green or red points to change the path and see the white circle following it. I already made a prototype like this one, you can find it in this post, but using Phaser 3 features made the whole process easier and more powerful. First, the curve you see and you can change is a Bezier curve created by Phaser with only one line. Once you change one of the four points defining the curve, the curve itself updates in real time, so there is no need to calculate it again. I found this feature very useful. The curve can also be drawn in a graphics object with just one line. What about the tween? Instead of tweening the sprite, we tween an object value from zero to 1, that is from the beginning to the end of the curve, then we create a callback to be fired at each tween update, find the point on the curve according to the tweening value – yes, again with just one line of code – then update the sprite position. This was awesome. Have a look at the source code, still uncommented but quite easy to understand:
var game;

window.onload = function() {
    var gameConfig = {
        type: Phaser.WEBGL,
        width: 600,
        height: 600,
        backgroundColor: 0x000000,
        scene: [playGame]
    };
    game = new Phaser.Game(gameConfig);
    window.focus()
    resize();
    window.addEventListener("resize", resize, false);
}

class playGame extends Phaser.Scene{
    constructor(){
        super("PlayGame");
    }
    preload(){
        this.load.image("point", "point.png");
	}
	create(){
        var pointColors = ["0x00ff00", "0x008800", "0x880000", "0xff0000"];
        this.bezierGraphics = this.add.graphics();
        this.pointsArray = [];
        for(var i = 0; i < 4; i++){
            var draggablePoint = this.add.image(Phaser.Math.Between(100, game.config.width - 100), Phaser.Math.Between(100, game.config.height - 100), "point");
            draggablePoint.setTint(pointColors[i]);
            draggablePoint.setInteractive();
            this.pointsArray[i] = draggablePoint;
        }
        this.bezierCurve = new Phaser.Curves.CubicBezier(this.pointsArray[0], this.pointsArray[1], this.pointsArray[2], this.pointsArray[3]);
        this.input.setDraggable(this.pointsArray);
        this.input.on("drag", function (pointer, gameObject, posX, posY){
            gameObject.x = posX;
            gameObject.y = posY;
            this.drawBezier();
        }, this);
        this.movingPoint = this.add.image(0, 0, "point");
        this.movingPoint.scaleX = 0.5;
        this.movingPoint.scaleY = 0.5;
        this.drawBezier();
        var tweenObject = {
            val: 0
        }
        this.tweens.add({
            targets: tweenObject,
            val: 1,
            duration: 2000,
            yoyo: true,
            repeat: -1,
            ease: "Sine.easeInOut",
            callbackScope: this,
            onUpdate: function(tween, target){
                var position = this.bezierCurve.getPoint(target.val);
                this.movingPoint.x = position.x;
                this.movingPoint.y = position.y;
            }
        });
      }
      drawBezier(){
          this.bezierGraphics.clear();
          this.bezierGraphics.lineStyle(4, 0xffffff);
          this.bezierCurve.draw(this.bezierGraphics);
          this.bezierGraphics.lineStyle(2, 0x00ff00);
          this.bezierGraphics.beginPath();
          this.bezierGraphics.moveTo(this.pointsArray[0].x, this.pointsArray[0].y);
          this.bezierGraphics.lineTo(this.pointsArray[1].x, this.pointsArray[1].y);
          this.bezierGraphics.strokePath();
          this.bezierGraphics.lineStyle(2, 0xff0000);
          this.bezierGraphics.beginPath();
          this.bezierGraphics.moveTo(this.pointsArray[2].x, this.pointsArray[2].y);
          this.bezierGraphics.lineTo(this.pointsArray[3].x, this.pointsArray[3].y);
          this.bezierGraphics.strokePath();
      }
}

function resize() {
    var canvas = document.querySelector("canvas");
    var windowWidth = window.innerWidth;
    var windowHeight = window.innerHeight;
    var windowRatio = windowWidth / windowHeight;
    var gameRatio = game.config.width / game.config.height;
    if(windowRatio < gameRatio){
        canvas.style.width = windowWidth + "px";
        canvas.style.height = (windowWidth / gameRatio) + "px";
    }
    else{
        canvas.style.width = (windowHeight * gameRatio) + "px";
        canvas.style.height = windowHeight + "px";
    }
}
This concept will be applied to my latest Down the Mountain prototype to add a more realistic 3D effect when the player jumps. Download the source code.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

215 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stairs
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers