Creating a Pong Clone in Phaser.JS (Part 2)

Making the AI Paddle

//declaring our P1 controlled paddle at X 10 and Y 300 (half of our canvas size)paddleP1 = this.physics.add.image(10, 300, “paddle1”);
import paddle2 from “../assets/paddle2.png”;let paddleP2;preload: function preload() {this.load.image("bg", bg);this.load.image("paddle1", paddle1);this.load.image("paddle2", paddle2);this.load.image("star", star);},create: function create() {this.add.image(400, 300, "bg");this.add.image("paddle1", paddle1);this.add.image("paddle2", paddle2)//declaring our P2 controlled paddle at X 790 (right side of canvas) and Y 300 (half of our canvas size)paddleP2 = this.physics.add.image(790, 300, "paddle2");//setting paddleP1 bouncepaddleP2.setBounce(1, 1);//set worldcollisionbounds for P1 so it can't leave the playing fieldpaddleP2.setCollideWorldBounds(true);

Replace the Star Sprite with a ball

import ballimg from “../assets/ball.png”;let ball;

Implementing AI

//CPU logic — mimic the balls velocity on the Y axispaddleP2.body.setVelocity(ball.body.velocity.y);//move in the opposite X direction at half the speed (tweak for higher CPU difficulty)paddleP2.body.velocity.x = -ball.body.velocity.x * 0.5;//limit the max Y velocitypaddleP2.body.maxVelocity.y = 250;//limit the max X velocitypaddleP2.body.maxVelocity.X = 250;//update ball bounce per frameball.setBounce(1, 1);

Add Some Sound Effects

import blip1 from “../assets/4390__noisecollector__pongblipf-4.wav”;import blip2 from “../assets/4391__noisecollector__pongblipf-5.wav”;
preload: function preload() {this.load.image(“bg”, bg);this.load.image(“paddle1”, paddle1);this.load.image(“paddle2”, paddle2);this.load.image(“ballimg”, ballimg);“blip1”, blip1);“blip2”, blip2);
const processCollision = (paddleP1, ball) => {ball.setBounceY(Phaser.Math.FloatBetween(0.5, 0.8));ball.setBounce(1, 1);“blip2”);};const processCollision2 = (paddleP2, ball) => {ball.setBounceY(Phaser.Math.FloatBetween(0.5, 0.8));ball.setBounce(1, 1);“blip1”);};
this.physics.add.collider(ball, paddleP1, processCollision, null, this);//adding collision detection for paddleP2 and the starthis.physics.add.collider(ball, paddleP2, processCollision2, null, this);
  • adding and detecting scores
  • indicating which side a player starts on via colours
  • serving the ball from a player perspective
  • Serving the ball from beginning of the game
  • Serving the ball once scored against
  • Game over condition

About the Author

  • HTML5
  • JavaScript
  • JQuery
  • CSS3
  • MySQL/PostgreSQL
  • Bootstrap
  • MaterialUI
  • React
  • Redux



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store