Drawing Graphics in Phaser (Part 2)

 

Advanced Shapes (Primitives)

Carying on from my previous post, getting started with Phaser Graphics, we will look at using the moveTo and lineto function to draw some more complex shapes.


let group = this.add.group();

let graphics = this.game.make.graphics(0, 0);
graphics.lineStyle(1, 0xFFFFFF, 1);

// draw a square
graphics.lineTo(0, 50);
graphics.lineTo(50, 50);
graphics.lineTo(50, 0);
graphics.lineTo(0, 0)

group.add(graphics);

Drawing lines is very simple, just say where two points are on the canvas, and it will draw a line. as you can see above, we drew a square.

Lets use the Graphics.arc function to draw circles!


let group = this.add.group();

let graphics = this.game.make.graphics(0, 0);
graphics.lineStyle(1, 0xFFFFFF, 1);

// draw a circle
graphics.arc(75, 75, 50, 0, Math.PI*2, false);

// draw a semi-circle

graphics.arc(75, 75, 35, 0, Math.PI, false);

group.add(graphics);

phaser graphics primitive arc shapes

Drawing Smiley Faces – Arc


let group = this.add.group();

let graphics = this.game.make.graphics(0, 0);
graphics.lineStyle(1, 0xFFFFFF, 1);

graphics.arc(75, 75, 50, 0, Math.PI*2, false); // Outer circle
graphics.moveTo(110, 75);
graphics.arc(75, 75, 35, 0, Math.PI, false);  // Mouth (clockwise)
graphics.moveTo(65, 65);
graphics.arc(60, 65, 5, 0, Math.PI*2, false);  // Left eye
graphics.moveTo(95, 65);
graphics.arc(90, 65, 5, 0, Math.PI*2, false);  // Right eye

group.add(graphics);

Phaser graphics smile with arc function

Drawing Speech Bubble – Quadratic Curve To


let group = this.add.group();
let graphics = new Phaser.Graphics(250, 250);
graphics.lineStyle(1, 0xFFFFFF, 1);
graphics.moveTo(75,25);
graphics.quadraticCurveTo(25,25,25,62.5);
graphics.quadraticCurveTo(25,100,50,100);
graphics.quadraticCurveTo(50,120,30,125);
graphics.quadraticCurveTo(
graphics.quadraticCurveTo(125,100,125,62.5);
graphics.quadraticCurveTo(125,25,75,25);

group.add(graphics);

A little note for using quadratic curves, they function exactly the same except for accepting an additional parameters for the control point. You can read a very good tutorial on how quadratic curves work here.

Phaser Graphics Speech Bubble

Drawing Heart – Bezier Curve To


let group = this.add.group();

let graphics = new Phaser.Graphics(250, 250);
graphics.lineStyle(1, 0xFFFFFF, 1);
graphics.moveTo(75,40);
graphics.bezierCurveTo(75,37,70,25,50,25);
graphics.bezierCurveTo(20,25,20,62.5,20,62.5);
graphics.bezierCurveTo(20,80,40,102,75,120);
graphics.bezierCurveTo(110,102,130,80,130,62.5);
graphics.bezierCurveTo(130,62.5,130,25,100,25);
graphics.bezierCurveTo(85,25,75,37,75,40);

group.add(graphics);

Bezier curves are very similar to quadratic curves. There is another very good tutorial on how bezier curves work here.

heart bezier curve

I will go into detail about how to use input features and generating sprites from the graphics in part 3.