{"id":2419,"date":"2019-07-06T16:15:33","date_gmt":"2019-07-06T16:15:33","guid":{"rendered":"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/?p=2419"},"modified":"2022-11-26T13:45:27","modified_gmt":"2022-11-26T13:45:27","slug":"build-a-space-shooter-with-phaser3-and-javascripttutorial1","status":"publish","type":"post","link":"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/build-a-space-shooter-with-phaser3-and-javascripttutorial1\/","title":{"rendered":"Build a Space Shooter with Phaser3 and JavaScript(Tutorial1)"},"content":{"rendered":"\n<!-- Facebook Like Button v1.9.6 BEGIN [http:\/\/blog.bottomlessinc.com] -->\n<iframe src=\"http:\/\/www.facebook.com\/plugins\/like.php?href=http%3A%2F%2Finspiredtoeducate.net%2Finspiredtoeducate%2Fbuild-a-space-shooter-with-phaser3-and-javascripttutorial1%2F&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;colorscheme=light\" scrolling=\"no\" frameborder=\"0\" allowTransparency=\"true\" style=\"border:none; overflow:hidden; width:450px; height: 30px; align: left; margin: 2px 0px 2px 0px\"><\/iframe>\n<!-- Facebook Like Button END -->\n\r\n<p>Like many computer enthusiasts, I grew up playing video games on the classic Nintendo entertainment system.  Some of my favorite games included Super Mario brothers, Legend of Zelda, Tetris, and Star Force. It\u2019s been fun to share these game classics with my kids. They still find them fun. In this blog post series, I want to unpack building a 2D shooter game using Phaser3.js.  <a href=\"https:\/\/phaser.io\/\">Phaser3 <\/a>provides a robust and fast game framework for early stage JavaScript developers.<\/p>\r\n\r\n\r\n\r\n<p>From exploring the options in 2D game creation using Javascript, Phaser has grown an impressive community of game makers.  Here are a few game samples that you would want to explore.<\/p>\r\n\r\n\r\n\r\n<figure class=\"wp-block-image\"><img loading=\"lazy\" width=\"640\" height=\"384\" src=\"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-content\/uploads\/2019\/07\/sample.png\" alt=\"\" class=\"wp-image-2421\" srcset=\"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-content\/uploads\/2019\/07\/sample.png 640w, http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-content\/uploads\/2019\/07\/sample-300x180.png 300w\" sizes=\"(max-width: 640px) 100vw, 640px\" \/><figcaption>Space shooter assets from www.kenney.nl<\/figcaption><\/figure>\r\n\r\n\r\n\r\n<ul>\r\n\t<li><a href=\"http:\/\/robowhale.com\/html5\/submarine\/deploy\/\">Fun flappy birds clone<\/li>\r\n\t<li><a href=\"https:\/\/labs.phaser.io\/view.html?src=src%5Cgames%5Cbreakout%5Cbreakout.js\">Breakout<\/a><\/li>\r\n\t<li><a href=\"https:\/\/phaser.io\/examples\/v2\/games\/defender\">A Defender Clone<\/a><\/li>\r\n<\/ul>\r\n\r\n\r\n\r\n<p>In this post series, I wanted to collect a few resources, tools, and links to help you get started building a space shooter game with Phaser 3.   We&#8217;ll be drawing from the inspiration of classic games like Space Invaders.<\/p>\r\n\r\n\r\n\r\n<figure class=\"wp-block-image\"><img loading=\"lazy\" width=\"217\" height=\"248\" src=\"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-content\/uploads\/2019\/07\/SpaceInvaders-Gameplay.gif\" alt=\"\" class=\"wp-image-2420\"\/><\/figure>\r\n\r\n\r\n\r\n<p> In terms of JavaScript writing style, we\u2019re going to keep the code samples as simple as possible to express core concepts.  If you need to get started with JavaScript, I recommend checking out the free sources at <a href=\"https:\/\/www.codecademy.com\/learn\/introduction-to-javascript\">CodeAcademy<\/a> to start exploring the language. We\u2019ll be drawing inspiration from classic games like Galaga and Star Force.  Even though I\u2019m trying to unpack these ideas for early stage JavaScript coders, I also want to provide examples that leverage ES6 coding structures. The Phaser3 documentation does not focus on this style of code organization.  In general, I want to explore programming concepts that provide nice encapsulation and readability. We also want to make sure we can extend these coding patterns well.<\/p>\r\n\r\n\r\n\r\n<p>The game we\u2019re building may feel similar to this work here:<br> <a href=\"http:\/\/users.aber.ac.uk\/eds\/CS252_games\/mwg2\/JSGame\/\">http:\/\/users.aber.ac.uk\/eds\/CS252_games\/mwg2\/JSGame\/<\/a><\/p>\r\n\r\n\r\n\r\n<p>In this tutorial, we want to encourage you to setup your work environment with Visual Studio code.  You can also inspect the tutorial code in the following glitch sample.<\/p>\r\n\r\n\r\n\r\n<p><a href=\"https:\/\/glitch.com\/edit\/#!\/awg-tutorial?path=shooter.js:1:0\">https:\/\/glitch.com\/edit\/#!\/awg-tutorial?path=shooter.js:1:0<\/a><\/p>\r\n\r\n\r\n\r\n<h3><a id=\"Setting_up_Visual_Studio_Code_15\"><\/a>Setting up Visual Studio Code<\/h3>\r\n\r\n\r\n\r\n<p>In this series, I recommend setting up Visual Studio Code on your computer. It\u2019s a robust tool for web development and works well for JavaScript projects.  You can find <a href=\"https:\/\/code.visualstudio.com\/docs\/introvideos\/basics\">instructions to install VS Code using this link.<\/a>  I also recommend using the Visual Studio Code Live server extension to make it easier to hot re-load your code changes.   Please refer to the following video for details.  <\/p>\r\n\r\n\r\n\r\n<iframe loading=\"lazy\" width=\"\u201c560\u201d\" height=\"\u201c315\u201d\" src=\"https:\/\/www.youtube.com\/embed\/WzE0yqwbdgU\" frameborder=\"\u201c0\u201d\" allow=\"\u201caccelerometer;\" autoplay;=\"\" encrypted-media;=\"\" gyroscope;=\"\" picture-in-picture\u201d=\"\" allowfullscreen=\"\"><\/iframe>\r\n\r\n\r\n\r\n<h3><a id=\"Downloading_some_boilerplate_code_20\"><\/a>Downloading some boilerplate code<\/h3>\r\n\r\n\r\n\r\n<p>To save some time, I have organized a ZIP file with a collection of code and graphics that you can leverage in building your own shooter game.  You\u2019re encouraged to play and build with these assets, sounds, and code samples to elaborate on your own game.  For this first exercise, we just want to get a ship displayed to the screen and move it around using arrow keys.<\/p>\r\n\r\n\r\n\r\n<ul><li><a href=\"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-content\/uploads\/2019\/07\/AlienWarGame-Tutorial1.zip\">Download the boilerplate code from here.<\/a><\/li><li>Extract the ZIP file to a location on your computer.  We\u2019ll call this your working directory.  For me, I might store my files in \u201cc:\\alienWarGame-tutorial1.\u201d<\/li><\/ul>\r\n\r\n\r\n\r\n<h2><a id=\"Lets_explore_the_contents_of_this_boilerplate_code_27\"><\/a>Let\u2019s explore the contents of this boilerplate code<\/h2>\r\n\r\n\r\n\r\n<ul><li><strong>assets:<\/strong> The game art, sounds, sprite graphics have been created by Kenny Vleugels.  You can find his creative commons game art from his website here: <a href=\"https:\/\/www.kenney.nl\/assets\/space-shooter-redux\">https:\/\/www.kenney.nl\/assets\/space-shooter-redux<\/a><\/li><\/ul>\r\n\r\n\r\n\r\n<ul><li><strong>shooter.js: <\/strong>This JavaScript file will contain our game objects and behavior code.<\/li><li><strong>shooter.html:<\/strong> This HTML file provides a home for our JavaScript game code. (see the code below)  Please note that we\u2019re downloading phaser.js (version 3.11) from a content delivery network.  In the body of the HTML file, we import our shooter.js.  Remember to install &#8220;Live server&#8221; extension for Visual Studio.   You will be able to right click on the code HTML file and select &#8220;open with Live server.&#8221;  This will load the file on a small HTTP server on your computer.  All phaser games need to be hosted on a web server.<\/li><\/ul>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code><!doctype html>\r\n<html lang=\"en\">\r\n<head>\r\n    <meta charset=\"UTF-8\" \/>\r\n    <title>Space Shooter Tutorial 1<\/title>\r\n    <script src=\"\/\/cdn.jsdelivr.net\/npm\/phaser@3.11.0\/dist\/phaser.js\"><\/script>    \r\n    <style type=\"text\/css\">\r\n        body {\r\n            margin: 0;\r\n        }\r\n    <\/style>\r\n<\/head>\r\n<body>\r\n    <script src=\"shooter.js\"><\/script>    \r\n<\/body>\r\n<\/html><\/code><\/pre>\r\n\r\n\r\n\r\n<h3><a id=\"Breaking_Down_Shooterjs_50\"><\/a>Breaking Down Shooter.js<\/h3>\r\n\r\n\r\n\r\n<p>All Phaser games start with a little bit of configuration.  In this \u201cconfig\u201d object below, we establish a screen size of 800 pixels by 600 pixels.  This will be our drawing surface for the game.  To help detect if objects bump into each other, we will be leveraging the \u2018arcade\u2019 physics engine included in Phaser3.<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>var SCREEN_WIDTH = 800;\r\nvar SCREEN_HEIGHT = 600;\r\nvar config = {\r\n    type: Phaser.AUTO,\r\n    width: SCREEN_WIDTH,\r\n    height: SCREEN_HEIGHT,\r\n    physics: {\r\n        default: 'arcade'\r\n    }\r\n};<\/code><\/pre>\r\n\r\n\r\n\r\n<p>Ok. Let\u2019s build our Space ship player object. In Phaser 3, they have been working to improve the framework to leverage modern JavaScript features like <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Classes\">Es6 classes.<\/a>  The class will help us store the properties of the ship. Properties will include stuff like the location of the ship on the screen, object state, and texture.  The class will also include several methods for moving the ship around. In the constructor method, we accept a scene object and location on the screen. (x,y).  The call to \u201csuper\u201d and \u201csetPosition\u201d helps associate the sprite with the parent scene and location.  We call \u201csetTexture\u201d using the parameter of \u2018ship\u2019 to associate the ship graphic with the sprite.  Finally, we set some variables(deltaX, deltaY) to configure how much the ship will move when we press keys.<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>class Ship extends Phaser.GameObjects.Sprite  {\r\n\r\n    constructor(scene, x , y) {\r\n        super(scene, x, y);\r\n        this.setTexture('ship');\r\n        this.setPosition(x, y);\r\n        this.deltaX = 5;\r\n        this.deltaY = 5;\r\n    }\r\n\r\n    moveLeft() {\r\n        if (this.x > 0) {\r\n            this.x -= this.deltaX;\r\n        }\r\n    }\r\n\r\n    moveRight() {\r\n        if (this.x < SCREEN_WIDTH) {\r\n            this.x += this.deltaX;\r\n        }\r\n    }\r\n\r\n    moveUp() {\r\n        if (this.y > 0) {\r\n            this.y -= this.deltaY;\r\n        }\r\n    }\r\n\r\n    moveDown() {\r\n\r\n        if (this.y < SCREEN_HEIGHT) {\r\n            this.y += this.deltaY;\r\n        }\r\n    }\r\n\r\n    preUpdate(time, delta) {\r\n        super.preUpdate(time, delta);\r\n    }\r\n}<\/code><\/pre>\r\n\r\n\r\n\r\n<p>In the following method called \u2018moveLeft\u2019, we implement the math to move the sprite to the left.  Since we\u2019re moving left, we subtract 5 pixels from the current x position.  We only execute this code if x is greater than zero.  Most of the other movement methods operate in a similar manner.<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>    moveLeft() {\r\n        if (this.x > 0) {\r\n            this.x -= this.deltaX;\r\n        }\r\n    }<\/code><\/pre>\r\n\r\n\r\n\r\n<h3><a id=\"Lets_make_a_scene_119\"><\/a>Let\u2019s make a scene!<\/h3>\r\n\r\n\r\n\r\n<p>In the following class, we have to establish a Phaser scene object.  It has a few simple tasks.  In the \u201cpreload\u201d method, need we load the ship sprite graphic from our assets folder.<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>class Scene1 extends Phaser.Scene {\r\n\r\n    constructor(config) {\r\n        super(config);\r\n    }\r\n\r\n    preload() {\r\n        this.load.image('ship', 'assets\/SpaceShooterRedux\/PNG\/playerShip1_orange.png');\r\n    }\r\n\r\n    create() {\r\n        this.cursors = this.input.keyboard.createCursorKeys();\r\n        this.myShip = new Ship(this, 400, 500);\r\n        this.add.existing(this.myShip);\r\n    }\r\n\r\n    update() {\r\n        if (this.cursors.left.isDown) {\r\n            this.myShip.moveLeft();\r\n        }\r\n\r\n        if (this.cursors.right.isDown) {\r\n            this.myShip.moveRight();\r\n        }\r\n\r\n        if (this.cursors.up.isDown) {\r\n            this.myShip.moveUp();\r\n        }\r\n\r\n        if (this.cursors.down.isDown) {\r\n            this.myShip.moveDown();\r\n        }\r\n\r\n        if (this.cursors.space.isDown) {\r\n            \/\/ shooting guns goes here\r\n        }\r\n    }\r\n}<\/code><\/pre>\r\n\r\n\r\n\r\n<p>The create method has does additional setup for our scene.  We establish a property called cursors that will be used for detecting keyboard input like the arrow keys.  We also create a ship instance at (400,500) and add it to the scene.<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>    create() {\r\n        this.cursors = this.input.keyboard.createCursorKeys();\r\n        this.myShip = new Ship(this, 400, 500);\r\n        this.add.existing(this.myShip);\r\n    }<\/code><\/pre>\r\n\r\n\r\n\r\n<p>We now can start moving the ship around using the update method.  The if statements in update help us detect the various arrow keys.  We call the appropriate method on the ship.  In other words, if we press the LEFT button, we should call this.myShip.moveLeft().<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>    update() {\r\n        if (this.cursors.left.isDown) {\r\n            this.myShip.moveLeft();\r\n        }\r\n\r\n        if (this.cursors.right.isDown) {\r\n            this.myShip.moveRight();\r\n        }\r\n\r\n        if (this.cursors.up.isDown) {\r\n            this.myShip.moveUp();\r\n        }\r\n\r\n        if (this.cursors.down.isDown) {\r\n            this.myShip.moveDown();\r\n        }\r\n\r\n        if (this.cursors.space.isDown) {\r\n            \/\/ shooting guns goes here\r\n        }\r\n    }\r\n<\/code><\/pre>\r\n\r\n\r\n\r\n<p>Here\u2019s the final step, we associate our game configuration information to a new game.  We then add our scene.<\/p>\r\n\r\n\r\n\r\n<pre class=\"wp-block-code\"><code>var game = new Phaser.Game(config);\r\ngame.scene.add('scene1', Scene1, true, { x: 400, y: 300 });\r\n<\/code><\/pre>\r\n\r\n\r\n\r\n<p>If you're really excited to learn more, I have found the learning from the examples very helpful.<\/p>\r\n\r\n\r\n\r\n<p><a href=\"https:\/\/labs.phaser.io\/\">Phaser Labs Examples<\/a><\/p>\r\n\r\n\r\n\r\n<p><\/p>\r\n\r\n\r\n\r\n<h3>Play Time With Angular 15 and PhaserJS<\/h3>\r\n\r\n<p>Curious about building 2D games with web skills? In this online meetup, we'll explore tools and patterns to use PhaserJs and JavaScript to make engaging 2D games. We'll cover tools to make experiences with our favorite language: TypeScript. We'll also cover some cool updates from the latest release of Angular. Come join us to learn about the latest innovations from our Angular community. Look forward to connecting with like-minded Orlando developers and designers. Hope you can join us! Make sure to bring a friend too!<\/p>\r\n\r\n<ul>\r\n<li> WHEN: Nov 29th at 6:30pm <\/li>\r\n<li> WHERE: Online!! <\/li>\r\n<li>Please register using the link below<\/li>\r\n<li>\r\n\t<a href=\"https:\/\/gdg.community.dev\/events\/details\/google-gdg-central-florida-presents-play-time-with-angular-15-and-phaserjs\/\">\r\n\tJoin us for GDG Central Florida Meetup\r\n\t<\/a>\r\n<\/li>\r\n<\/ul>\r\n\r\n\r\n\r\n\n<!-- Facebook Like Button v1.9.6 BEGIN [http:\/\/blog.bottomlessinc.com] -->\n<iframe src=\"http:\/\/www.facebook.com\/plugins\/like.php?href=http%3A%2F%2Finspiredtoeducate.net%2Finspiredtoeducate%2Fbuild-a-space-shooter-with-phaser3-and-javascripttutorial1%2F&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;colorscheme=light\" scrolling=\"no\" frameborder=\"0\" allowTransparency=\"true\" style=\"border:none; overflow:hidden; width:450px; height: 30px; align: left; margin: 2px 0px 2px 0px\"><\/iframe>\n<!-- Facebook Like Button END -->\n","protected":false},"excerpt":{"rendered":"<p>Like many computer enthusiasts, I grew up playing video games on the classic Nintendo entertainment system. Some of my favorite games included Super Mario brothers, Legend of Zelda, Tetris, and Star Force. It\u2019s been fun to share these game classics with my kids. They still find them fun. In this [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[7,23,11],"tags":[],"_links":{"self":[{"href":"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-json\/wp\/v2\/posts\/2419"}],"collection":[{"href":"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-json\/wp\/v2\/comments?post=2419"}],"version-history":[{"count":9,"href":"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-json\/wp\/v2\/posts\/2419\/revisions"}],"predecessor-version":[{"id":2695,"href":"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-json\/wp\/v2\/posts\/2419\/revisions\/2695"}],"wp:attachment":[{"href":"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-json\/wp\/v2\/media?parent=2419"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-json\/wp\/v2\/categories?post=2419"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-json\/wp\/v2\/tags?post=2419"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}