{"id":2442,"date":"2019-07-17T10:35:59","date_gmt":"2019-07-17T10:35:59","guid":{"rendered":"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/?p=2442"},"modified":"2019-07-17T10:48:06","modified_gmt":"2019-07-17T10:48:06","slug":"build-a-space-shooter-with-phaser3-and-javascripttutorial2","status":"publish","type":"post","link":"https:\/\/inspiredtoeducate.net\/inspiredtoeducate\/build-a-space-shooter-with-phaser3-and-javascripttutorial2\/","title":{"rendered":"Build a Space Shooter with Phaser3 and JavaScript(Tutorial2)"},"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=https%3A%2F%2Finspiredtoeducate.net%2Finspiredtoeducate%2Fbuild-a-space-shooter-with-phaser3-and-javascripttutorial2%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\n<p> In this blog post series, I want to unpack building a 2D shooter game using <a rel=\"noreferrer noopener\" aria-label=\"Phaser3.js (opens in a new tab)\" href=\"https:\/\/phaser.io\/\" target=\"_blank\">Phaser3.js<\/a>. Phaser3 provides a robust and fast game framework for early-stage JavaScript developers.  In this post, we&#8217;ll focus on enabling our ship to fire lasers.  <\/p>\n\n\n\n<figure class=\"wp-block-image is-resized\"><img loading=\"lazy\" src=\"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-content\/uploads\/2019\/07\/lasers-shooting.gif\" alt=\"Space shooter\" class=\"wp-image-2443\" width=\"400\" height=\"300\"\/><\/figure>\n\n\n\n<p>Please make sure to check out <a href=\"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/build-a-space-shooter-with-phaser3-and-javascripttutorial1\/\">Tutorial 1 to get started with this project.  You&#8217;ll need to build upon the code and ideas from the previous blog post<\/a>.<br><br>Let&#8217;s start by creating a game object to represent a laser. (see code below)  We&#8217;ll model this object using the ShipLaser class that extends Phaser.GameObjects.Sprite.  In general, a class connects data stuff and related functions(or methods) in a nice little package.  In this case, the laser has data properties like location(x,y), a texture, speed, and a scene. This code snippet has two methods: constructor and preUpdate.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class ShipLaser extends Phaser.GameObjects.Sprite {\n\n\tconstructor(scene, x, y) {\n    \tsuper(scene, x, y);\n    \tthis.setTexture('laser');\n    \tthis.setPosition(x, y);\n    \tthis.speed = 10;\n    \tthis.scene = scene;\n    \tscene.physics.world.enable(this);\n\t}\n\n\tpreUpdate(time, delta) {\n    \tif(this.active == false){return;}\n    \tsuper.preUpdate(time, delta);\n    \tthis.y -= this.speed;\n\t}\n}<\/code><\/pre>\n\n\n\n<p>The constructor method enables us to set up the ShipLaser class.  We&#8217;ll initialize properties like texture, position, speed, and physics. <br>In Phaser 3, the preUpdate method of a sprite enables us to describe behavior or movement of the sprite.   The framework requires that we call &#8220;super.preUpdate.&#8221;  On the next line, we move the sprite upward on the screen by subtracting from the y property.  <\/p>\n\n\n\n<p>Let&#8217;s make some edits to our Ship class.  We&#8217;re going to store a reference of the scene.  To describe how fast the ship moves over the game space, we initial deltaX and deltaY to 5.  In this current design, we&#8217;re going to store the list of lasers from the ship in an array.  We also need to store some information related to when the last shot was executed. <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Ship extends Phaser.GameObjects.Sprite  {\n\n\tconstructor(scene, x , y) {\n    \t\/\/ ... other setup stuff\n\n    \tthis.scene = scene;\n    \tthis.deltaX = 5;\n    \tthis.deltaY = 5;\n    \tthis.lasers = new Array();\n    \tthis.lastShot = new Date().getTime();\n    \tthis.shotFrequency = 250;\n\t}<\/code><\/pre>\n\n\n\n<p> It&#8217;s time to shoot stuff!  Let&#8217;s define a method to fireLasers from the ship.  When my kids play this game, they just keep their fingers down on the space bar the whole time. \ud83d\ude42 By design, we want to control how often the laser gets shot.  We start by checking the current time.  The quantity of currentTime &#8211; lastShot returns the number of milliseconds since the last shot.   If this value is greater than 250, we allow the ship to fire.<br><br>When we fire, we create an instance of the ShipLaser we defined.  Notice that the ship laser will be created with the same scene and location as the ship.   Once we have an instance, we add the laser instance to the scene.   We finish up by storing the laser in our lasers list and updating the &#8220;lastShot&#8221; time. <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\tfireLasers() {\n    \tvar currentTime = new Date().getTime();\n    \tif (currentTime - this.lastShot > this.shotFrequency) {\n        \tvar shipLaser = new ShipLaser(this.scene, this.x, this.y);\n        \tthis.scene.add.existing(shipLaser);\n        \tthis.lasers.push(shipLaser);\n        \tthis.lastShot = currentTime;\n    \t}\n\t}<\/code><\/pre>\n\n\n\n<p>\n\nWe have to make one more edit to our Ship class to make the lasers function properly.  The &#8220;preUpdate&#8221; javascript function enables us to describe behavior associated with our sprite.  The game framework calls this function on every game tick.  In the following code snippet, we&#8217;re going to remove laser objects that have reached the top of the screen.  We start by building an array of lasers to remove from the scene.   In the first loop, we search for lasers that have reached the top of the screen.  (i.e. lasers[i].y &lt;= 0)  In the second loop, we remove the laser objects from the ship and destroy them.  If you create game objects, it&#8217;s important to clean them up if you&#8217;re not using them.\n\n<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\tpreUpdate(time, delta) {\n    \tsuper.preUpdate(time, delta);\n\n    \tvar i = 0;\n    \tvar j = 0;\n    \tvar lasersToRemove = new Array();\n\n    \tfor (i = 0; i &lt; this.lasers.length; i++) {\n        \tif (this.lasers[i].y &lt;= 0) {\n            \tlasersToRemove.push(this.lasers[i]);\n        \t}\n    \t}\n\n    \tfor (j = 0; j &lt; lasersToRemove.length; j++) {\n        \tvar laserIndex = this.lasers.indexOf(lasersToRemove[j]);\n        \tthis.lasers.splice(laserIndex, 1);\n        \tlasersToRemove[j].destroy();\n    \t}\n\t}<\/code><\/pre>\n\n\n\n<p> In the scene1 class, we need to add one more detail.  The laser should fire when the user presses the space bar.  Let&#8217;s edit the update method to fire the lasers.  <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>```javascript\n    update() {\n        if (this.cursors.space.isDown) {\n            this.myShip.fireLasers();\n        }\n        \n```<\/code><\/pre>\n\n\n\n<p>If you&#8217;re interested in reviewing the completed code tutorial, feel free to visit <a href=\"https:\/\/github.com\/michaelprosario\/alienwargames\/blob\/tutorial2\/shooter.js\">my GitHub tutorial link<\/a>.    <\/p>\n\n\n\n<p>In the next post, we&#8217;ll add some alien targets for our game.  We&#8217;ll see you next time!  <\/p>\n\n\n\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=\"Space shooter graphic\" class=\"wp-image-2421\" srcset=\"https:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-content\/uploads\/2019\/07\/sample.png 640w, https:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-content\/uploads\/2019\/07\/sample-300x180.png 300w\" sizes=\"(max-width: 640px) 100vw, 640px\" \/><\/figure>\n\n\n\n<p>If you\u2019re really excited to learn more, I have found the learning from the examples very helpful.<\/p>\n\n\n\n<p><a href=\"https:\/\/labs.phaser.io\/\">Phaser Labs Examples<\/a><\/p>\n\n\n\n<p>JavaScript Posts from InspiredToEducate.NET<\/p>\n\n\n\n<ul><li> <a href=\"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/aframe-building-webvr-experiences-with-html-and-javascript\/\">AFrame: Building WebVR experiences with HTML and JavaScript<\/a><\/li><li> <a href=\"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/using-android-javascript-and-arduino-to-control-your-robot-makered-javascript-android\/\">Using Android, JavaScript, and Arduino to control your robot. <\/a><\/li><li> <a href=\"http:\/\/inspiredtoeducate.net\/inspiredtoeducate\/build-a-space-shooter-with-phaser3-and-javascripttutorial1\/\">Build a Space Shooter with Phaser3 and JavaScript(Tutorial1) <\/a><\/li><\/ul>\n\n\n\n<p><br> <br><\/p>\n\n<!-- Facebook Like Button v1.9.6 BEGIN [http:\/\/blog.bottomlessinc.com] -->\n<iframe src=\"http:\/\/www.facebook.com\/plugins\/like.php?href=https%3A%2F%2Finspiredtoeducate.net%2Finspiredtoeducate%2Fbuild-a-space-shooter-with-phaser3-and-javascripttutorial2%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>In this blog post series, I want to unpack building a 2D shooter game using Phaser3.js. Phaser3 provides a robust and fast game framework for early-stage JavaScript developers. In this post, we&#8217;ll focus on enabling our ship to fire lasers. Please make sure to check out Tutorial 1 to get [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[8],"tags":[],"_links":{"self":[{"href":"https:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-json\/wp\/v2\/posts\/2442"}],"collection":[{"href":"https:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-json\/wp\/v2\/comments?post=2442"}],"version-history":[{"count":5,"href":"https:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-json\/wp\/v2\/posts\/2442\/revisions"}],"predecessor-version":[{"id":2449,"href":"https:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-json\/wp\/v2\/posts\/2442\/revisions\/2449"}],"wp:attachment":[{"href":"https:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-json\/wp\/v2\/media?parent=2442"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-json\/wp\/v2\/categories?post=2442"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/inspiredtoeducate.net\/inspiredtoeducate\/wp-json\/wp\/v2\/tags?post=2442"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}