class Example extends Phaser.Scene {
this.load.image("pig", "https://assets.codepen.io/9367036/pig.png");
this.load.image("chicken", "https://assets.codepen.io/9367036/chicken.png");
this.load.image("ball", "https://assets.codepen.io/9367036/boulder.png");
this.pigPath = new Phaser.Curves.Path(150, 100).lineTo(300, 300);
this.chickenPath = new Phaser.Curves.Path(650, 200).circleTo(100);
const pigStartPoint = this.pigPath.getPoint(0);
const chickenStartPoint = this.chickenPath.getPoint(0);
this.pig = this.physics.add
.image(pigStartPoint.x, pigStartPoint.y, "pig")
this.pig.body.allowGravity = false;
this.pig.body.setCircle(70);
this.chicken = this.physics.add
.image(chickenStartPoint.x, chickenStartPoint.y, "chicken")
this.chicken.body.allowGravity = false;
this.chicken.body.setCircle(70);
const graphics = this.add.graphics();
graphics.lineStyle(3, 0xffffff, 0.1);
this.pigPath.draw(graphics);
this.chickenPath.draw(graphics);
const pigTweenDuration = 1000;
const chickenTweenDuration = 2000;
this.pigSpeed = this.calculateSpeed(this.pigPath, pigTweenDuration);
this.chickenSpeed = this.calculateSpeed(
this.balls = this.physics.add.group({
setXY: { x: 100, y: 100, stepX: 10 }
this.balls.children.iterate(function (ball) {
ball.setCollideWorldBounds(true);
Phaser.Math.Between(-500, 500),
Phaser.Math.Between(-500, 500)
let radius = ball.width / 2;
ball.body.setCircle(radius);
this.physics.add.collider(this.balls, this.pig);
this.physics.add.collider(this.balls, this.chicken);
this.pigT = { value: 0 };
duration: pigTweenDuration,
this.chickenT = { value: 0 };
duration: chickenTweenDuration,
const desiredPigPosition = this.pigPath.getPoint(this.pigT.value);
const pigDirection = new Phaser.Math.Vector2(
desiredPigPosition.x - this.pig.x,
desiredPigPosition.y - this.pig.y
this.pig.body.setVelocity(
pigDirection.x * this.pigSpeed,
pigDirection.y * this.pigSpeed
const desiredChickenPosition = this.chickenPath.getPoint(
const chickenDirection = new Phaser.Math.Vector2(
desiredChickenPosition.x - this.chicken.x,
desiredChickenPosition.y - this.chicken.y
this.chicken.body.setVelocity(
chickenDirection.x * this.chickenSpeed,
chickenDirection.y * this.chickenSpeed
calculateSpeed(path, duration) {
const length = path.getLength();
const durationInSeconds = duration / 1000;
return length / durationInSeconds;
const game = new Phaser.Game(config);