SlideShare a Scribd company logo
1 of 81
Download to read offline
Piotr Kowalski
"My 10 days with Phaser.js"
2015-09-16
@piecioshka
Who am I?
Kierownik Działu Aplikacji Webowych
Cyfrowy Polsat, Warsaw
JavaScript Ninja. Mac lover. Pebble evangelist.
Organizer WarsawJS
"Kto chce szuka sposobu, kto nie chce szuka powodu."
piecioshka.pl/blog github.com/piecioshka
twitter.com/piecioshka soundcloud.com/piecioshka
Where am I?
I made a game
dragonballplay.com
Advantages of Phaser.js
• Big community
• A lot of lines of code (a lot of JSDocs)
• Good quality of code (components)
• Separation of layers in API, e.g. states and
keyboards
• Cool phaser.io/docs
Disadvantages of Phaser.js
• I didn't notice...
"State idea"
• The gameplay is based on state switching , e.g.
choose language, select character from menu,
fight, defeat or win
• State definition - class with 4 methods: preload ,
create , update , render and optionally init
• Only one state is active !
init method
• It runs as the first method
preload method
• Method which downloads the assets
• images
• sounds
• json files
create method
• Runs ones while generating the state
• In that method I create all objects that are
occurring in a game state
update method
• Phaser.Game#raf via
requestAnimationFrame or setTimeout
• 38881: Phaser.Game#update
• The core game loop
render method
• Method runs after update process
• Inside it we can enable displaying debug
details
Day I: Here we go!
31↑
Use ECMAScript 6.
webpack and Babel.js take care of compiling
to ECMAScript 5 (for browser).
“
webpack.config.js
module.exports = {
resolve: { extensions: ['.es6.js', '.js', ''] },
entry: './app/scripts/main',
output: {
filename: 'bundle.js',
path: './app/dist'
},
module: { loaders: [{
test: /.es6.js/,
exclude: /node_modules/,
loader: 'babel?stage=0'
}] }
}
01.
02.
03.
04.
05.
06.
07.
08.
09.
10.
11.
12.
13.
Advantages of ECMAScript 6
• Modules - no global variables
• Importing - require only dependency
• Smooth syntax of class definition with cool inheritance
• Default parameters and Arrow function
// Destructuring assignment
let [x, y] = ['abc', 100]
// x = 'abc', y = 100
01.
02.
03.
HTML (index.html)
No more HTML files, because everything is in the Canvas.
1. Create container for game: <div id="game"></div>
2. Add library file: scripts/vendor/phaser.js
3. Add our game file: dist/bundle.js
Phaser.js v2.4.3
Type Files
Normal 2.8M phaser.js
726K phaser.min.js
Only need to 2,2M phaser-arcade-physics.js
754K phaser-arcade-physics.map
567K phaser-arcade-physics.min.js
Why not in modules?
• Throw an error: "PIXI is not defined"
• webpack will have big file to manage
• Do I really need it?
Write first lines of code
• Create a game object
// Create game object
this.game = new Phaser.Game(800, 400, Phaser.Canvas, 'game`)
• One for all game
• Available from the each of game state
01.
02.
Day II: Design (vol. 1)
157 LOC (126↑)
• Add states: MenuState - select character
// Add state to set
this.game.state.add(name, handler)
// Activate passed state
this.game.state.start(name)
01.
02.
03.
04.
Day II: Design (vol. 2)
• assets - directory contains everything except code,
e.g. graphics , sound
• Display first in game background - simple image with game
dimension and position in point 0,0
// Load image file and put it to cache
this.load.image(key, path)
// Fetch from cache image and put to Canvas
this.add.image(x, y, key)
01.
02.
03.
04.
Day II: Design (vol. 3)
• scripts/models/ directory with characters definition, e.g. Son Goku
• Add states: FightState , SearchingState (screen with collected balls)
• scripts/configuration.js - file in isolated game configuration
• Create instance of player class
• Add some buttons
// Add button to Canvas
this.add.button(x, y, key, handler)
01.
02.
The first big problem
• Sharing objects between states?
Ideas?
• Global variables?
• Never!
• Create custom game properties!
Day III: We are moving!
258 LOC (101↑)
• Create map with Tiled - cool tool for create game maps
this.load.tilemap(key, path, data, format)
// data: if `path` was passed, equals null
// format: Phaser.Tilemap.TILED_JSON
• Add tileset to map (our spritesheet)
this.load.spritesheet(key, path, width, height)
// width: tile width
// height: tile height
• Create layer on map and extend it to the whole game area
01.
02.
03.
01.
02.
03.
Balls positions
• Definition of positions dragon balls in separate files, for why?
• backend can generate that files
• separate configuration from business logic
• Loading JSON file
// Fetch file and put response into cache
this.load.json(key, path)
// Return parsed object
object = this.cache.getJSON(key)
01.
02.
03.
04.
Create the first sprite - character
// Add sprite to game
this.add.sprite(x, y, key)
Add dragon balls
• Create group object for them, for better collision management
01.
02.
Simple message
• Create message
// Add label
message = this.add.text(x, y, text)
• Animation: fadeIn
message.alpha = 0
this.add.tween(message).to(config, time, type, true)
// config: { alpha: 1 }
// time: Phaser.Timer.SECOND
// type: Phaser.Easing.Linear.None
01.
02.
01.
02.
03.
04.
05.
Navigation vol. 1
if (keyboard.isDown(Phaser.Keyboard.LEFT) {
player.x -= 5
}
Warning!
If we would like to use collision detection,
we should update player.velocity.x not only player.x .
01.
02.
03.
Navigation vol. 2
// Update velocity of player
player.velocity.x -= 5
Remember to clear velocity before that process!
// Reset velocity
player.velocity.x = 0
01.
02.
“01.
02.
Collision - a very broad subject
• Player
// Enable arcade mode for our player
this.physics.arcade.enable(player)
• Map
map.setCollisionByIndex(1) // Start counting from 1
layer = map.createLayer(name)
this.physics.arcade.collide(player, layer)
Player will be collide with tile with index = 0 from now!
01.
02.
01.
02.
03.
Collected items - dragon balls
• Group of balls should have a body
balls = this.add.group()
balls.enableBody = true
• Group should have defined a physics
// Add body to group of balls
this.physics.arcade.enable(balls)
// Start collide between player and group of balls
this.physics.arcade.collide(player, balls, handler)
01.
02.
01.
02.
03.
04.
Day IV: Time from clock
384 LOC (126↑)
• Create states: ShenronState , GameOverState ,
TrainingState
• Handle keyboard on MenuState
• Create countdown - measure time to GameOver
// Clock with reference to state
this.time.events.add(time, handler, context)
01.
02.
Day V: Music!
710 LOC (326↑)
• Create fake spritesheets for characters
• Add logo and sound
this.load.audio(key, path)
sound = this.add.audio(key)
sound.play()
• Create enemies on FightState
• Resize hitbox during fight
• Create state MealState - regeneration state, HP will be reset
01.
02.
03.
Day VI: Display bars
858 LOC (148↑)
• Display player labels (HP and EXP),
and player avatars on FightState
• Disable sound globally (saved state in localStorage )
• Add everywhere we can DragonBallPlay logo
Day VII: Player collision
1028 LOC (170↑)
• Support mouse events on MenuState
// Support mouse over
button.events.onInputOver.add(handler, context)
• Check players collision
isOverlap() => {
return this.physics.arcade.overlap(player, enemy)
}
• Decrease HP of enemy when player hits him
01.
02.
01.
02.
03.
Day VIII: Create Artificial
Intelligence
1270 LOC (242↑)
• Create screen which create only message
• Display game control before main part of game
• Rename FightState to VersusState - better name
• FightState is base class with children VersusState and
TrainingState
• First idea for AI - create list of enemy moves
Day IX: Easter egg
1533 LOC (263↑)
• Fixed AI - choose random move from predefined list
• Create Utilities module with static methods
• Create state: LanguageState
• Detach all text to isolated JSON files
• Create DefinitionTyped.js
• Revert default player parameters on GameOverState
• Create Easter Egg : new character available on MenuState
Day X: Last day
1732 LOC (199↑)
• Rename SearchingState to CollectingState
• Choose randomly 1 map from 3 on CollectingState
• Add collision with 2 tiles: 1 and 3
// Upgrade collision
map.setCollision([1, 3])
• Converting all images to PNG - why is it a bad idea for backgrounds?
• Create states: PlayerPresentationState , EnemyPresentationState ,
WinnerState
01.
02.
Future plans
• Block players moves when someone dies on VersusState
• Add countdown on TrainingState
• Display app version somewhere with small font size
• Extend display time for MessageState
• Fixed players collision, that they can't enter on themselves
• Support shortcuts
• Fixed Konami code
• Support Gamepad API
• Support Notification API
• Draw characters and create simple favicon
The worst part
of code
scripts/states/VersusState.es6.js
The best part
of code
scripts/main.es6.js
What I learned?
• Draw something when you are finish implementation
• Keyboard handler doesn't have to be in update method
• Each of state has his own clock , which is destroyed
when state is destroyed
My mistakes
• Duplicate code
Phaser.State#rnd.integerInRange(min, max)
instead of:
Utilities.random(min, max)
• I missed the manager to keep the storyline, so I decided to...
buy a couple of books about Phaser.js
Donation
patreon.com/photonstorm
(Richard Davey @photonstorm)
Thanks!
Links
• Slides: http://piecioshka.github.io/warsawjs-presentation-my-10-days-with-phaser-js
• My games:
• https://github.com/piecioshka/www.dragonballplay.com [COMPLETE]
• https://github.com/javascript-ninjas/game-fastest-joby [COMPLETE]
• https://github.com/piecioshka/ss15-dumplings [COMPLETE]
• https://github.com/piecioshka/game-electrode [WIP]
• https://github.com/piecioshka/game-snooker [WIP]
• ECMAScript 7: https://babeljs.io/docs/usage/experimental
• Special editor: http://phasereditor.boniatillo.com
• Font: http://www.dafont.com/saiyan-sans.font
See you next
month at
WarsawJS

More Related Content

What's hot

Albion Online - A Cross-Platform MMO (Unite Europe 2016, Amsterdam)
Albion Online - A Cross-Platform MMO (Unite Europe 2016, Amsterdam)Albion Online - A Cross-Platform MMO (Unite Europe 2016, Amsterdam)
Albion Online - A Cross-Platform MMO (Unite Europe 2016, Amsterdam)David Salz
 
Building Multiplayer Games (w/ Unity)
Building Multiplayer Games (w/ Unity)Building Multiplayer Games (w/ Unity)
Building Multiplayer Games (w/ Unity)Noam Gat
 
East Coast DevCon 2014: The Slate UI Framework - Architecture & Tools
East Coast DevCon 2014: The Slate UI Framework - Architecture & ToolsEast Coast DevCon 2014: The Slate UI Framework - Architecture & Tools
East Coast DevCon 2014: The Slate UI Framework - Architecture & ToolsGerke Max Preussner
 
Teacher Training Workshop - Game Development with Phaser
Teacher Training Workshop  - Game Development with PhaserTeacher Training Workshop  - Game Development with Phaser
Teacher Training Workshop - Game Development with PhaserPablo Farías Navarro
 
Deterministic Simulation - What modern online games can learn from the Game B...
Deterministic Simulation - What modern online games can learn from the Game B...Deterministic Simulation - What modern online games can learn from the Game B...
Deterministic Simulation - What modern online games can learn from the Game B...David Salz
 
Tools for Tabletop Game Design
Tools for Tabletop Game DesignTools for Tabletop Game Design
Tools for Tabletop Game DesignMartin Grider
 
Using Ubuntu
Using UbuntuUsing Ubuntu
Using Ubunturr1955
 
Game development with Cocos2d
Game development with Cocos2dGame development with Cocos2d
Game development with Cocos2dVinsol
 
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法Unite2017Tokyo
 
iOS Game Development With UIKit
iOS Game Development With UIKitiOS Game Development With UIKit
iOS Game Development With UIKitMartin Grider
 
Absolutist: Porting to major platforms within a minute
Absolutist: Porting to major platforms within a minuteAbsolutist: Porting to major platforms within a minute
Absolutist: Porting to major platforms within a minuteDevGAMM Conference
 
A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig)
A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig)   A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig)
A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig) David Salz
 
OGDC2013_ Spine Animation_ Mr Alviss Ha
OGDC2013_ Spine Animation_ Mr Alviss HaOGDC2013_ Spine Animation_ Mr Alviss Ha
OGDC2013_ Spine Animation_ Mr Alviss Haogdc
 
Rapid Game Development with RUby and Gosu – Ruby Manor 4
Rapid Game Development with RUby and Gosu – Ruby Manor 4Rapid Game Development with RUby and Gosu – Ruby Manor 4
Rapid Game Development with RUby and Gosu – Ruby Manor 4benko
 
Deploy All The Games
Deploy All The GamesDeploy All The Games
Deploy All The GamesAdam Hill
 
Designing and Testing Firefox 4
Designing and Testing Firefox 4Designing and Testing Firefox 4
Designing and Testing Firefox 4Anthony Chung
 
Practical guide to optimization in Unity
Practical guide to optimization in UnityPractical guide to optimization in Unity
Practical guide to optimization in UnityDevGAMM Conference
 
W3C HTML5 KIG-The near future of the web platform
 W3C HTML5 KIG-The near future of the web platform W3C HTML5 KIG-The near future of the web platform
W3C HTML5 KIG-The near future of the web platformChanghwan Yi
 

What's hot (19)

Albion Online - A Cross-Platform MMO (Unite Europe 2016, Amsterdam)
Albion Online - A Cross-Platform MMO (Unite Europe 2016, Amsterdam)Albion Online - A Cross-Platform MMO (Unite Europe 2016, Amsterdam)
Albion Online - A Cross-Platform MMO (Unite Europe 2016, Amsterdam)
 
Building Multiplayer Games (w/ Unity)
Building Multiplayer Games (w/ Unity)Building Multiplayer Games (w/ Unity)
Building Multiplayer Games (w/ Unity)
 
East Coast DevCon 2014: The Slate UI Framework - Architecture & Tools
East Coast DevCon 2014: The Slate UI Framework - Architecture & ToolsEast Coast DevCon 2014: The Slate UI Framework - Architecture & Tools
East Coast DevCon 2014: The Slate UI Framework - Architecture & Tools
 
Teacher Training Workshop - Game Development with Phaser
Teacher Training Workshop  - Game Development with PhaserTeacher Training Workshop  - Game Development with Phaser
Teacher Training Workshop - Game Development with Phaser
 
Deterministic Simulation - What modern online games can learn from the Game B...
Deterministic Simulation - What modern online games can learn from the Game B...Deterministic Simulation - What modern online games can learn from the Game B...
Deterministic Simulation - What modern online games can learn from the Game B...
 
Tools for Tabletop Game Design
Tools for Tabletop Game DesignTools for Tabletop Game Design
Tools for Tabletop Game Design
 
Using Ubuntu
Using UbuntuUsing Ubuntu
Using Ubuntu
 
Game development with Cocos2d
Game development with Cocos2dGame development with Cocos2d
Game development with Cocos2d
 
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
【Unite 2017 Tokyo】インスタンシングを用いた美麗なグラフィックの実現方法
 
iOS Game Development With UIKit
iOS Game Development With UIKitiOS Game Development With UIKit
iOS Game Development With UIKit
 
Absolutist: Porting to major platforms within a minute
Absolutist: Porting to major platforms within a minuteAbsolutist: Porting to major platforms within a minute
Absolutist: Porting to major platforms within a minute
 
A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig)
A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig)   A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig)
A simple and powerful property system for C++ (talk at GCDC 2008, Leipzig)
 
OGDC2013_ Spine Animation_ Mr Alviss Ha
OGDC2013_ Spine Animation_ Mr Alviss HaOGDC2013_ Spine Animation_ Mr Alviss Ha
OGDC2013_ Spine Animation_ Mr Alviss Ha
 
Rapid Game Development with RUby and Gosu – Ruby Manor 4
Rapid Game Development with RUby and Gosu – Ruby Manor 4Rapid Game Development with RUby and Gosu – Ruby Manor 4
Rapid Game Development with RUby and Gosu – Ruby Manor 4
 
Deploy All The Games
Deploy All The GamesDeploy All The Games
Deploy All The Games
 
Designing and Testing Firefox 4
Designing and Testing Firefox 4Designing and Testing Firefox 4
Designing and Testing Firefox 4
 
Practical guide to optimization in Unity
Practical guide to optimization in UnityPractical guide to optimization in Unity
Practical guide to optimization in Unity
 
Pong
PongPong
Pong
 
W3C HTML5 KIG-The near future of the web platform
 W3C HTML5 KIG-The near future of the web platform W3C HTML5 KIG-The near future of the web platform
W3C HTML5 KIG-The near future of the web platform
 

Similar to My 10 days with Phaser.js - WarsawJS Meetup #13

Bringing Supernatural Thriller, "Oxenfree" to Nintendo Switch
Bringing Supernatural Thriller, "Oxenfree" to Nintendo SwitchBringing Supernatural Thriller, "Oxenfree" to Nintendo Switch
Bringing Supernatural Thriller, "Oxenfree" to Nintendo SwitchUnity Technologies
 
Game object models - Game Engine Architecture
Game object models - Game Engine ArchitectureGame object models - Game Engine Architecture
Game object models - Game Engine ArchitectureShawn Presser
 
Unreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal EditorUnreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal EditorNick Pruehs
 
Thomas Blair Portfolio
Thomas Blair PortfolioThomas Blair Portfolio
Thomas Blair PortfolioBlixtev
 
iOS 2D Gamedev @ CocoaHeads
iOS 2D Gamedev @ CocoaHeadsiOS 2D Gamedev @ CocoaHeads
iOS 2D Gamedev @ CocoaHeadsAlain Hufkens
 
React Native Evening
React Native EveningReact Native Evening
React Native EveningTroy Miles
 
Sephy engine development document
Sephy engine development documentSephy engine development document
Sephy engine development documentJaejun Kim
 
Get Into Sprite Kit
Get Into Sprite KitGet Into Sprite Kit
Get Into Sprite Kitwaynehartman
 
Supersize Your Production Pipe
Supersize Your Production PipeSupersize Your Production Pipe
Supersize Your Production Pipeslantsixgames
 
98 374 Lesson 06-slides
98 374 Lesson 06-slides98 374 Lesson 06-slides
98 374 Lesson 06-slidesTracie King
 
IntroToEngineDevelopment.pdf
IntroToEngineDevelopment.pdfIntroToEngineDevelopment.pdf
IntroToEngineDevelopment.pdfzakest1
 
Supersize your production pipe enjmin 2013 v1.1 hd
Supersize your production pipe    enjmin 2013 v1.1 hdSupersize your production pipe    enjmin 2013 v1.1 hd
Supersize your production pipe enjmin 2013 v1.1 hdslantsixgames
 
Mongo or Die: How MongoDB Powers Doodle or Die
Mongo or Die: How MongoDB Powers Doodle or DieMongo or Die: How MongoDB Powers Doodle or Die
Mongo or Die: How MongoDB Powers Doodle or DieAaron Silverman
 
Maximize Your Production Effort (English)
Maximize Your Production Effort (English)Maximize Your Production Effort (English)
Maximize Your Production Effort (English)slantsixgames
 
Multiplayer game with angular and firebase
Multiplayer game with angular and firebaseMultiplayer game with angular and firebase
Multiplayer game with angular and firebaseMichael Haberman
 

Similar to My 10 days with Phaser.js - WarsawJS Meetup #13 (20)

Bringing Supernatural Thriller, "Oxenfree" to Nintendo Switch
Bringing Supernatural Thriller, "Oxenfree" to Nintendo SwitchBringing Supernatural Thriller, "Oxenfree" to Nintendo Switch
Bringing Supernatural Thriller, "Oxenfree" to Nintendo Switch
 
Game object models - Game Engine Architecture
Game object models - Game Engine ArchitectureGame object models - Game Engine Architecture
Game object models - Game Engine Architecture
 
Unreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal EditorUnreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal Editor
 
Cocos2d programming
Cocos2d programmingCocos2d programming
Cocos2d programming
 
Soc research
Soc researchSoc research
Soc research
 
Thomas Blair Portfolio
Thomas Blair PortfolioThomas Blair Portfolio
Thomas Blair Portfolio
 
iOS 2D Gamedev @ CocoaHeads
iOS 2D Gamedev @ CocoaHeadsiOS 2D Gamedev @ CocoaHeads
iOS 2D Gamedev @ CocoaHeads
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
 
Sephy engine development document
Sephy engine development documentSephy engine development document
Sephy engine development document
 
Cocos2d game programming 2
Cocos2d game programming 2Cocos2d game programming 2
Cocos2d game programming 2
 
Get Into Sprite Kit
Get Into Sprite KitGet Into Sprite Kit
Get Into Sprite Kit
 
Supersize Your Production Pipe
Supersize Your Production PipeSupersize Your Production Pipe
Supersize Your Production Pipe
 
Html5 game development
Html5 game developmentHtml5 game development
Html5 game development
 
98 374 Lesson 06-slides
98 374 Lesson 06-slides98 374 Lesson 06-slides
98 374 Lesson 06-slides
 
IntroToEngineDevelopment.pdf
IntroToEngineDevelopment.pdfIntroToEngineDevelopment.pdf
IntroToEngineDevelopment.pdf
 
Supersize your production pipe enjmin 2013 v1.1 hd
Supersize your production pipe    enjmin 2013 v1.1 hdSupersize your production pipe    enjmin 2013 v1.1 hd
Supersize your production pipe enjmin 2013 v1.1 hd
 
Mongo or Die: How MongoDB Powers Doodle or Die
Mongo or Die: How MongoDB Powers Doodle or DieMongo or Die: How MongoDB Powers Doodle or Die
Mongo or Die: How MongoDB Powers Doodle or Die
 
Maximize Your Production Effort (English)
Maximize Your Production Effort (English)Maximize Your Production Effort (English)
Maximize Your Production Effort (English)
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 
Multiplayer game with angular and firebase
Multiplayer game with angular and firebaseMultiplayer game with angular and firebase
Multiplayer game with angular and firebase
 

Recently uploaded

VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...masabamasaba
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 

Recently uploaded (20)

VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 

My 10 days with Phaser.js - WarsawJS Meetup #13

  • 1. Piotr Kowalski "My 10 days with Phaser.js" 2015-09-16 @piecioshka
  • 2. Who am I? Kierownik Działu Aplikacji Webowych Cyfrowy Polsat, Warsaw JavaScript Ninja. Mac lover. Pebble evangelist. Organizer WarsawJS "Kto chce szuka sposobu, kto nie chce szuka powodu."
  • 4. I made a game
  • 6. Advantages of Phaser.js • Big community • A lot of lines of code (a lot of JSDocs) • Good quality of code (components) • Separation of layers in API, e.g. states and keyboards • Cool phaser.io/docs
  • 7. Disadvantages of Phaser.js • I didn't notice...
  • 8. "State idea" • The gameplay is based on state switching , e.g. choose language, select character from menu, fight, defeat or win • State definition - class with 4 methods: preload , create , update , render and optionally init • Only one state is active !
  • 9. init method • It runs as the first method
  • 10. preload method • Method which downloads the assets • images • sounds • json files
  • 11. create method • Runs ones while generating the state • In that method I create all objects that are occurring in a game state
  • 12. update method • Phaser.Game#raf via requestAnimationFrame or setTimeout • 38881: Phaser.Game#update • The core game loop
  • 13. render method • Method runs after update process • Inside it we can enable displaying debug details
  • 14. Day I: Here we go! 31↑ Use ECMAScript 6. webpack and Babel.js take care of compiling to ECMAScript 5 (for browser). “
  • 15. webpack.config.js module.exports = { resolve: { extensions: ['.es6.js', '.js', ''] }, entry: './app/scripts/main', output: { filename: 'bundle.js', path: './app/dist' }, module: { loaders: [{ test: /.es6.js/, exclude: /node_modules/, loader: 'babel?stage=0' }] } } 01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13.
  • 16. Advantages of ECMAScript 6 • Modules - no global variables • Importing - require only dependency • Smooth syntax of class definition with cool inheritance • Default parameters and Arrow function // Destructuring assignment let [x, y] = ['abc', 100] // x = 'abc', y = 100 01. 02. 03.
  • 17. HTML (index.html) No more HTML files, because everything is in the Canvas. 1. Create container for game: <div id="game"></div> 2. Add library file: scripts/vendor/phaser.js 3. Add our game file: dist/bundle.js
  • 18. Phaser.js v2.4.3 Type Files Normal 2.8M phaser.js 726K phaser.min.js Only need to 2,2M phaser-arcade-physics.js 754K phaser-arcade-physics.map 567K phaser-arcade-physics.min.js
  • 19. Why not in modules? • Throw an error: "PIXI is not defined" • webpack will have big file to manage • Do I really need it?
  • 20. Write first lines of code • Create a game object // Create game object this.game = new Phaser.Game(800, 400, Phaser.Canvas, 'game`) • One for all game • Available from the each of game state 01. 02.
  • 21.
  • 22. Day II: Design (vol. 1) 157 LOC (126↑) • Add states: MenuState - select character // Add state to set this.game.state.add(name, handler) // Activate passed state this.game.state.start(name) 01. 02. 03. 04.
  • 23. Day II: Design (vol. 2) • assets - directory contains everything except code, e.g. graphics , sound • Display first in game background - simple image with game dimension and position in point 0,0 // Load image file and put it to cache this.load.image(key, path) // Fetch from cache image and put to Canvas this.add.image(x, y, key) 01. 02. 03. 04.
  • 24. Day II: Design (vol. 3) • scripts/models/ directory with characters definition, e.g. Son Goku • Add states: FightState , SearchingState (screen with collected balls) • scripts/configuration.js - file in isolated game configuration • Create instance of player class • Add some buttons // Add button to Canvas this.add.button(x, y, key, handler) 01. 02.
  • 25. The first big problem • Sharing objects between states? Ideas? • Global variables? • Never! • Create custom game properties!
  • 26.
  • 27. Day III: We are moving! 258 LOC (101↑) • Create map with Tiled - cool tool for create game maps this.load.tilemap(key, path, data, format) // data: if `path` was passed, equals null // format: Phaser.Tilemap.TILED_JSON • Add tileset to map (our spritesheet) this.load.spritesheet(key, path, width, height) // width: tile width // height: tile height • Create layer on map and extend it to the whole game area 01. 02. 03. 01. 02. 03.
  • 28. Balls positions • Definition of positions dragon balls in separate files, for why? • backend can generate that files • separate configuration from business logic • Loading JSON file // Fetch file and put response into cache this.load.json(key, path) // Return parsed object object = this.cache.getJSON(key) 01. 02. 03. 04.
  • 29. Create the first sprite - character // Add sprite to game this.add.sprite(x, y, key) Add dragon balls • Create group object for them, for better collision management 01. 02.
  • 30. Simple message • Create message // Add label message = this.add.text(x, y, text) • Animation: fadeIn message.alpha = 0 this.add.tween(message).to(config, time, type, true) // config: { alpha: 1 } // time: Phaser.Timer.SECOND // type: Phaser.Easing.Linear.None 01. 02. 01. 02. 03. 04. 05.
  • 31. Navigation vol. 1 if (keyboard.isDown(Phaser.Keyboard.LEFT) { player.x -= 5 } Warning! If we would like to use collision detection, we should update player.velocity.x not only player.x . 01. 02. 03.
  • 32. Navigation vol. 2 // Update velocity of player player.velocity.x -= 5 Remember to clear velocity before that process! // Reset velocity player.velocity.x = 0 01. 02. “01. 02.
  • 33. Collision - a very broad subject • Player // Enable arcade mode for our player this.physics.arcade.enable(player) • Map map.setCollisionByIndex(1) // Start counting from 1 layer = map.createLayer(name) this.physics.arcade.collide(player, layer) Player will be collide with tile with index = 0 from now! 01. 02. 01. 02. 03.
  • 34. Collected items - dragon balls • Group of balls should have a body balls = this.add.group() balls.enableBody = true • Group should have defined a physics // Add body to group of balls this.physics.arcade.enable(balls) // Start collide between player and group of balls this.physics.arcade.collide(player, balls, handler) 01. 02. 01. 02. 03. 04.
  • 35.
  • 36. Day IV: Time from clock 384 LOC (126↑) • Create states: ShenronState , GameOverState , TrainingState • Handle keyboard on MenuState • Create countdown - measure time to GameOver // Clock with reference to state this.time.events.add(time, handler, context) 01. 02.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41. Day V: Music! 710 LOC (326↑) • Create fake spritesheets for characters • Add logo and sound this.load.audio(key, path) sound = this.add.audio(key) sound.play() • Create enemies on FightState • Resize hitbox during fight • Create state MealState - regeneration state, HP will be reset 01. 02. 03.
  • 42.
  • 43. Day VI: Display bars 858 LOC (148↑) • Display player labels (HP and EXP), and player avatars on FightState • Disable sound globally (saved state in localStorage ) • Add everywhere we can DragonBallPlay logo
  • 44.
  • 45. Day VII: Player collision 1028 LOC (170↑) • Support mouse events on MenuState // Support mouse over button.events.onInputOver.add(handler, context) • Check players collision isOverlap() => { return this.physics.arcade.overlap(player, enemy) } • Decrease HP of enemy when player hits him 01. 02. 01. 02. 03.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50. Day VIII: Create Artificial Intelligence 1270 LOC (242↑) • Create screen which create only message • Display game control before main part of game • Rename FightState to VersusState - better name • FightState is base class with children VersusState and TrainingState • First idea for AI - create list of enemy moves
  • 51.
  • 52.
  • 53.
  • 54.
  • 55. Day IX: Easter egg 1533 LOC (263↑) • Fixed AI - choose random move from predefined list • Create Utilities module with static methods • Create state: LanguageState • Detach all text to isolated JSON files • Create DefinitionTyped.js • Revert default player parameters on GameOverState • Create Easter Egg : new character available on MenuState
  • 56.
  • 57.
  • 58.
  • 59. Day X: Last day 1732 LOC (199↑) • Rename SearchingState to CollectingState • Choose randomly 1 map from 3 on CollectingState • Add collision with 2 tiles: 1 and 3 // Upgrade collision map.setCollision([1, 3]) • Converting all images to PNG - why is it a bad idea for backgrounds? • Create states: PlayerPresentationState , EnemyPresentationState , WinnerState 01. 02.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71. Future plans • Block players moves when someone dies on VersusState • Add countdown on TrainingState • Display app version somewhere with small font size • Extend display time for MessageState • Fixed players collision, that they can't enter on themselves • Support shortcuts • Fixed Konami code • Support Gamepad API • Support Notification API • Draw characters and create simple favicon
  • 76. What I learned? • Draw something when you are finish implementation • Keyboard handler doesn't have to be in update method • Each of state has his own clock , which is destroyed when state is destroyed
  • 77. My mistakes • Duplicate code Phaser.State#rnd.integerInRange(min, max) instead of: Utilities.random(min, max) • I missed the manager to keep the storyline, so I decided to... buy a couple of books about Phaser.js
  • 80. Links • Slides: http://piecioshka.github.io/warsawjs-presentation-my-10-days-with-phaser-js • My games: • https://github.com/piecioshka/www.dragonballplay.com [COMPLETE] • https://github.com/javascript-ninjas/game-fastest-joby [COMPLETE] • https://github.com/piecioshka/ss15-dumplings [COMPLETE] • https://github.com/piecioshka/game-electrode [WIP] • https://github.com/piecioshka/game-snooker [WIP] • ECMAScript 7: https://babeljs.io/docs/usage/experimental • Special editor: http://phasereditor.boniatillo.com • Font: http://www.dafont.com/saiyan-sans.font
  • 81. See you next month at WarsawJS