create account

Making Ping Pong Game With Phaser 3 (Part-1) by onepice

View this thread on: hive.blogpeakd.comecency.com
· @onepice ·
$28.07
Making Ping Pong Game With Phaser 3 (Part-1)
![ping-pong.JPG](https://cdn.steemitimages.com/DQmZ2vWFpuSTVyGmMs2jm5a7wTWFPRRGR9FgrA22JVX3k7Z/ping-pong.JPG)

# Repository

<a href="https://github.com/photonstorm/phaser">Phaser</a>

<a href="https://github.com/onepicesteem">My Github Profile</a>

<a href="https://github.com/onepicesteem/Making-Ping-Pong-Game-With-Phaser-3-Part-1">Making Ping Pong Game With Phaser 3 (Part-1)</a>

# What Will I Learn?

- You will learn how to program games using the `Phaser 3` library.
- You will learn how to make Phaser 3 `game settings`.
- You will learn how to `upload  and draw` pictures with Phaser 3.
- You will learn `keyboard controls` with phaser 3 .
- You will learn to move a dynamic object.
- You will learn `createCursorKeys()` function.
- You will learn `setVelocityY()` and , setVelocityX()` functions.
- You will learn `setCollideWorldBounds(true)`

# Requirements

Have basic html5 and javascript knowledge.
<a href="https://atom.io/">Atom Editor</a>

# Difficulty

- Basic

# Tutorial Contents

In this article I will show you how to do `ping-pong game` with `phaser 3`.

In my previous articles, I used to mention game programming using `pablojs`, but pablojs didn't fully meet the game development needs because it enabled the creation of svg objects.

I had to fix problems and write extra code when use pablojs.

I needed game engines to write an advanced game. I can make my games easier with a library designed for `2D games`.

Here is a great library prepared for 2d games with `phaser 3`.

I'm here with how to do ping-pong game using phaser 3.

In order to better explain this game I've divided it into two parts and here's the first part:

- I will create the necessary settings for the game.
- I will upload pictures to be used in the game.
- I will install keyboard controls to move objects in the game.
- I'm going to set the limits of the game to prevent objects from protruding from the limits of the game.

Let’s start.

First, I would like to talk about project files.

I will use `script.js` to write the `index.html` page and javascript codes to set the html page and of course we need a library of `phaser 3`.

- index.html
- script.js
- phaser3.js

Let's create a folder named `assets` for the pictures that will be used in the game and put the pictures in the ball, ground and the two players in this folder.
<div>
https://cdn.steemitimages.com/DQmf8o7joS1Q7Y75kynYeNNfNET3yQJp1so8LXUQu4NAjwx/ball.png
https://cdn.steemitimages.com/DQmQZUW3oJEMg2mdtwimDgx7WhoeQWd63CqazQ8wLRbK6kg/pc.png
https://cdn.steemitimages.com/DQmPfWXzwwuSNT9bukxNUb14iYZqWCESk9YGZGyBPGzwqjP/player.png
</div>

### Setting The index.html Page

We won't have much work with `index.html` when using `phaser 3`. It is enough upload the necessary files.
```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="phaser.js"></script>
    <script src="script.js"></script>
    <title>Document</title>
    <style type="text/css">
        body {
            margin: 0;
        }
    </style>
</head>
<body>
    
</body>
</html>
```
<br>
We still do the margin adjustment.

We have installed the `script.js` and `phaser.js` files.

### Making Game Settings

The `Phaser.Game()` class is used to create a game with phaser 3. The game class takes the settings of the game as a parameter and creates the game according to these settings.

With the settings of the game you can adjust the size of the playing field and the type of the game.
In script.js
```
var config = {
    type: Phaser.AUTO,
    width: 800,
    height: 400
};

var game = new Phaser.Game(config);
```
<br>
When such a setting is made, the playground is set to have a black background and `800x400`.

#### Screenshot 1
![jquery1.JPG](https://cdn.steemitimages.com/DQmTwiVK8VYmT5kCGZBFRWTv6zzUHC3WkSe7vYrotaZoE4w/jquery1.JPG)
<br>
With the `type` property, we can adjust the rendering context of the game. In phaser 3 the game can be set in the form of `Phaser.CANVAS` and `Phaser.WEBGL`.

When the `Phaser.AUTO` property is set, it is set to the WEBGL, but the WEBGL is automatically switched to the CANVAS system when the browser does not support it.

With the `scene` feature in the config setting, we can define the necessary functions for the game.
These necessary functions:

With the `preload` setting, the function to load the pictures to be used in the game is defined.
With the `create` setting, the function that creates the objects to be used in the game is defined.
With the `update` setting, the function that defines recurring events with specific time intervals is created.

```
var config = {
    type: Phaser.AUTO,
    width: 800,
    height: 400,
    scene: {
        preload: preloadGame,
        create: createGame,
  update: updateGame
    }
};
function preloadGame ()
{
//function where images are loaded
}

function createGame ()
{
//function in which objects are created
}

function updateGame ()
{
//repeated events at certain time intervals
}

```
<br>
### Image Upload Operations

I said, the background color is initially black. Let's change the background with the help of a picture.

Let's prepare the background image for the game in the `preloadGame()` function.
```
function preloadGame ()
 {
  this.load.image('ground','assets/ground.png');
 }
```
<br>
I set the keyword of `ground.png` as `ground`.

I set the background image to `800x400`. After loading, let's draw in the game area within the `createGame()` function.
```
function createGame ()
{
  this.add.image(400, 200, 'ground');
}
```
<br>
With phaser 3, the center points are centered when pictures are drawn to the screen.

An 800x400 sized image is placed at 400x200 for a full placement on a 800x400 sized playground.

#### Screenshot 2
![jquery2.JPG](https://cdn.steemitimages.com/DQmeKaJ55MdRzGX1o7GGxmeNaEHvzLfKyDHQ6GYaCx1Bx3n/jquery2.JPG)
<br>
### Providing Keyboard Control

For keyboard control, the `createCursorKeys()` function in input.keyboard api is used, but this function provides access to the keyboard's directional keys and some special keys such as space, shift.

Let's create the `cursor` variable and define the createCursorKeys() function.
```
var cursors;
function createGame ()
{

  cursors = this.input.keyboard.createCursorKeys();//keyboard Access
  console.log(cursor);
}
```
<br>
#### Screenshot 3
![jquery3.JPG](https://cdn.steemitimages.com/DQmfG5AzAie1nLxpb6TBEHwsXk9kEvmNCwVwVgTsyTvcqRH/jquery3.JPG)
<br>
With the keyboard keys, let's create our first pile to provide movement.
```
function preloadGame ()
 {
  this.load.image('ground','assets/ground.png');
  this.load.image('player','assets/player.png');
 }
```
<br>
```
var player;
function createGame ()
{
    this.add.image(400, 200, 'ground');

    cursor = this.input.keyboard.createCursorKeys();
    console.log(cursor);

    player = this.physics.add.sprite(780, 200, 'player');
}
```
<br>
We used different methods to draw the player object  and the background image on the screen.

Because the background image is a static object, we created it as `add.image`, but we have created `physics.add.sprite` because the player object will be a moving image.

To use the physics object, we need to define it in game settings.
```
var config = {
    type: Phaser.AUTO,
    width: 800,
    height: 400,
    physics: {
        default: 'arcade'
    },
    scene: {
        preload: preloadGame,
        create: createGame,
        update: updateGame
    }
};
```
<br>
#### Screenshot 4
![jquery4.JPG](https://cdn.steemitimages.com/DQmbPsveZMAy3S5EkjgPfrfvFCpEYB9XPk2M2niNoHe6vse/jquery4.JPG)
<br>
### Move With Keyboard

To move an object with the keyboard, we need to capture the moment the keyboard keys are pressed.

This process must be defined in the `updateGame()` function because it is a process that needs to be constantly checked.
```
function updateGame ()
{
  if(cursor.up.isDown)// move up if the up key is pressed
  {
    player.setVelocityY(-150);
  }
  else if(cursor.down.isDown)// move down if the down key is pressed
  {
    player.setVelocityY(150);
  }
  else//stop if no key is pressed.
  {
    player.setVelocityY(0);
  }

}
```
<br>
Using the `setVelocityY()` function, we can move up or down on dynamic objects. if we want to move a dynamic object to the right or left, we need to use `setVelocityX()`.

The following shows the movement of the visual player object.

#### Screenshot 5

![ezgif1.gif](https://cdn.steemitimages.com/DQmRNVFz987dZtzogTgBXsDLKqdmZWtVvyd9jbARJ9y9H7t/ezgif1.gif)
<br>

The player object passes the limits of the game world as seen. we can use `setCollideWorldBounds(true)` to fix this problem.

In the createGame () function, let's collide the player object with the world boundaries.
```
function createGame ()
{
player.setCollideWorldBounds(true);
}
```
<br>
So our dynamic object, as in the picture below, cannot exceed the limits.

#### Screenshot 6
![ezgif2.gif](https://cdn.steemitimages.com/DQmQW3UeWTNcc91wqx3138Wsbv6szYviVXkracFaRQ5w2fX/ezgif2.gif)
<br>

# Proof of Work Done

https://github.com/onepicesteem/Making-Ping-Pong-Game-With-Phaser-3-Part-1
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
properties (23)
authoronepice
permlinkmaking-ping-pong-game-with-phaser-3-part-1
categoryutopian-io
json_metadata{"tags":["utopian-io","tutorials","phaser-3","ping-pong"],"image":["https://cdn.steemitimages.com/DQmZ2vWFpuSTVyGmMs2jm5a7wTWFPRRGR9FgrA22JVX3k7Z/ping-pong.JPG","https://cdn.steemitimages.com/DQmf8o7joS1Q7Y75kynYeNNfNET3yQJp1so8LXUQu4NAjwx/ball.png","https://cdn.steemitimages.com/DQmQZUW3oJEMg2mdtwimDgx7WhoeQWd63CqazQ8wLRbK6kg/pc.png","https://cdn.steemitimages.com/DQmPfWXzwwuSNT9bukxNUb14iYZqWCESk9YGZGyBPGzwqjP/player.png","https://cdn.steemitimages.com/DQmTwiVK8VYmT5kCGZBFRWTv6zzUHC3WkSe7vYrotaZoE4w/jquery1.JPG","https://cdn.steemitimages.com/DQmeKaJ55MdRzGX1o7GGxmeNaEHvzLfKyDHQ6GYaCx1Bx3n/jquery2.JPG","https://cdn.steemitimages.com/DQmfG5AzAie1nLxpb6TBEHwsXk9kEvmNCwVwVgTsyTvcqRH/jquery3.JPG","https://cdn.steemitimages.com/DQmbPsveZMAy3S5EkjgPfrfvFCpEYB9XPk2M2niNoHe6vse/jquery4.JPG","https://cdn.steemitimages.com/DQmRNVFz987dZtzogTgBXsDLKqdmZWtVvyd9jbARJ9y9H7t/ezgif1.gif","https://cdn.steemitimages.com/DQmQW3UeWTNcc91wqx3138Wsbv6szYviVXkracFaRQ5w2fX/ezgif2.gif"],"links":["https://github.com/photonstorm/phaser","https://github.com/onepicesteem","https://github.com/onepicesteem/Making-Ping-Pong-Game-With-Phaser-3-Part-1","https://atom.io/"],"app":"steemit/0.1","format":"markdown"}
created2018-10-16 08:30:27
last_update2018-10-16 08:30:27
depth0
children6
last_payout2018-10-23 08:30:27
cashout_time1969-12-31 23:59:59
total_payout_value21.250 HBD
curator_payout_value6.824 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length9,213
author_reputation9,626,549,398,383
root_title"Making Ping Pong Game With Phaser 3 (Part-1)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id73,396,857
net_rshares22,145,320,553,691
author_curate_reward""
vote details (44)
@steem-ua ·
#### Hi @onepice!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
**Feel free to join our [@steem-ua Discord server](https://discord.gg/KpBNYGz)**
properties (22)
authorsteem-ua
permlinkre-making-ping-pong-game-with-phaser-3-part-1-20181016t113708z
categoryutopian-io
json_metadata"{"app": "beem/0.20.7"}"
created2018-10-16 11:37:09
last_update2018-10-16 11:37:09
depth1
children0
last_payout2018-10-23 11:37:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length286
author_reputation23,214,230,978,060
root_title"Making Ping Pong Game With Phaser 3 (Part-1)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id73,405,833
net_rshares0
@utopian-io ·
Hey, @onepice!

**Thanks for contributing on Utopian**.
We’re already looking forward to your next contribution!

**Get higher incentives and support Utopian.io!**
 Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via [SteemPlus](https://chrome.google.com/webstore/detail/steemplus/mjbkjgcplmaneajhcbegoffkedeankaj?hl=en) or [Steeditor](https://steeditor.app)).

**Want to chat? Join us on Discord https://discord.gg/h52nFrV.**

<a href='https://steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
authorutopian-io
permlinkre-making-ping-pong-game-with-phaser-3-part-1-20181022t193513z
categoryutopian-io
json_metadata"{"app": "beem/0.20.1"}"
created2018-10-22 19:35:15
last_update2018-10-22 19:35:15
depth1
children0
last_payout2018-10-29 19:35:15
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length589
author_reputation152,955,367,999,756
root_title"Making Ping Pong Game With Phaser 3 (Part-1)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id73,837,113
net_rshares0
@yalzeee ·
This is a really nice tutorial. I am a JavaScript ionic developer and would sometime in future want to combine ionic and phaser into the same project so that it'll have a nice gui before gameplay and even an awesome and efficient gameplay provided by phaser. This nicely explains ways that I could add phaser to an ionic App. Thanks for the tutorial.
properties (22)
authoryalzeee
permlinkre-onepice-making-ping-pong-game-with-phaser-3-part-1-20181017t221143341z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"app":"steemit/0.1"}
created2018-10-17 22:11:48
last_update2018-10-17 22:11:48
depth1
children0
last_payout2018-10-24 22:11:48
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length350
author_reputation12,484,565,044,191
root_title"Making Ping Pong Game With Phaser 3 (Part-1)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id73,509,377
net_rshares0
@yokunjon ·
$7.73
I thank you for your contribution. Here are my thoughts. Note that, my thoughts are my personal ideas on your post and they are not directly related to the review and scoring unlike the answers I gave in the questionnaire;

* **Structure**

  * Titles show what your post is about, so use them wisely. When defining titles, choosing and positioning words is essential to gain the user's attention. Giving general words priority than the rest is the key to achieve that. I advise you to put "Phaser 3" ahead of the title.

  * I advise you to consider using paragraphs. Separating each sentence with a blank line makes it harder to read and understand.

* **Language**

  * Some of your sentences are artificial. This makes them hard to read and understand. To overcome that, I advise you to check the structure of your sentences. For example, using "we" for each sentence in the post makes it boring to read. Here is an example sentence:

    * "Using the setVelocityY() function, we can move up or down on dynamic objects."

    * "By using the setVelocityY() function, it is possible to move dynamic objects on the Y-axis (up-down)."

    Instead of the one above, you can use the below one. It's not perfect nor mirror what you wrote, but it should be enough to make what I'm saying understood easily.

  * There are some sentences which are hard to understand because of the vocabulary and grammar. I advise you to proofread your posts before posting. It can increase the efficiency of your post.

* **Content**

  * In "requirements" section, I advise you to remove "atom" and write "any text editor (I will use atom in these tutorials)". Letting the user choose what to use is always better.

  * I advise you to set every general variable as a constant. As an example, you used 150 for speed. Instead of using 150, set it as "speed" in the settings section and do your calculations over that. For example, you can make it negative by -speed or speed * -1 depending on your taste. Same also applies to sprite dimensions.

  * You might consider changing topics to preserve some uniqueness. Similar content can be easily found on the internet. Being unique with tutorials on Utopian is not required, but preferable as we value rare posts more than others.

----
Your contribution has been evaluated according to [Utopian policies and guidelines](https://join.utopian.io/guidelines), as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, [click here](https://review.utopian.io/result/8/11222433).

---- 
Need help? Write a ticket on https://support.utopian.io/. 
Chat with us on [Discord](https://discord.gg/uTyJkNm). 
[[utopian-moderator]](https://join.utopian.io/)
πŸ‘  , , , , , , ,
properties (23)
authoryokunjon
permlinkre-onepice-making-ping-pong-game-with-phaser-3-part-1-20181016t095530525z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"links":["https://join.utopian.io/guidelines","https://review.utopian.io/result/8/11222433","https://support.utopian.io/","https://discord.gg/uTyJkNm","https://join.utopian.io/"],"app":"steemit/0.1"}
created2018-10-16 09:55:30
last_update2018-10-16 09:55:30
depth1
children2
last_payout2018-10-23 09:55:30
cashout_time1969-12-31 23:59:59
total_payout_value5.845 HBD
curator_payout_value1.883 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length2,757
author_reputation19,266,807,595,513
root_title"Making Ping Pong Game With Phaser 3 (Part-1)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id73,400,971
net_rshares6,090,497,292,807
author_curate_reward""
vote details (8)
@onepice ·
thank you for comment
πŸ‘  
properties (23)
authoronepice
permlinkre-yokunjon-re-onepice-making-ping-pong-game-with-phaser-3-part-1-20181016t103123891z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"app":"steemit/0.1"}
created2018-10-16 10:31:24
last_update2018-10-16 10:31:24
depth2
children0
last_payout2018-10-23 10:31:24
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length21
author_reputation9,626,549,398,383
root_title"Making Ping Pong Game With Phaser 3 (Part-1)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id73,402,750
net_rshares9,313,126,296
author_curate_reward""
vote details (1)
@utopian-io ·
Thank you for your review, @yokunjon!

So far this week you've reviewed 6 contributions. Keep up the good work!
πŸ‘  
properties (23)
authorutopian-io
permlinkre-re-onepice-making-ping-pong-game-with-phaser-3-part-1-20181016t095530525z-20181021t034513z
categoryutopian-io
json_metadata"{"app": "beem/0.20.1"}"
created2018-10-21 03:45:15
last_update2018-10-21 03:45:15
depth2
children0
last_payout2018-10-28 03:45:15
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length111
author_reputation152,955,367,999,756
root_title"Making Ping Pong Game With Phaser 3 (Part-1)"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id73,726,028
net_rshares10,007,704,124
author_curate_reward""
vote details (1)