Video summary
The tutorial begins by establishing a solid foundation for game development using Brackets and Replit, covering essential keyboard shortcuts, JavaScript basics like variables and data types, and control flow structures such as loops and functions. It delves into advanced topics including debugging with Chrome Developer Tools, regular expressions, array methods, and the nuances of scope and constructor functions. The initial setup involves creating a boilerplate project with an HTML skeleton and loading the Phaser library, while also addressing common issues like window resizing through the Scale Manager and organizing assets to ensure clarity across different screen sizes.
Once the environment is ready, the guide transitions into building complex game states and managing player interaction. Developers learn to create multiple scenes, switch between them using keyboard inputs, and implement camera logic that follows the player only within a defined dead zone. The tutorial covers integrating physics systems for collision detection, creating sprite sheets for smooth animations, and handling input events efficiently by using global helper functions to avoid repetitive code. Additional features include rotating characters based on movement direction, clamping vertical positions to prevent levitation, and utilizing tweens to animate properties like opacity and position with various easing effects.
As the project evolves, the focus shifts to implementing specific mechanics such as tile maps for level design, shooting systems with bullet groups, and UI interactions that play segmented audio effects. The course demonstrates how to create dynamic text generation that handles line wrapping correctly and integrates Google Fonts for custom typography. Advanced concepts like swipe detection algorithms are introduced to allow players to change direction via touch or mouse gestures, while a high-score system is built using Firebase as a real-time database to store and sort player achievements.
The final stages of the tutorial address practical troubleshooting and deployment considerations, such as resolving runtime errors by initializing missing database properties directly in the browser console. It also highlights the transition from older package managers like Bower to modern CDN approaches for installing dependencies like Firebase. By combining these technical skills with creative problem-solving, the video concludes by providing a comprehensive roadmap for building interactive games that feature particle effects, gravity-based platforming, and persistent data storage, empowering developers to create polished and functional projects ready for sharing.
Read the full video transcript
so before we start coding I think it's
important to know the keyboard shortcuts
because they greatly improve your
efficiency So eventually we're going to
be using the brackets text editor and
I'll be using these shortcuts and
brackets pretty frequently so the first
shortcut is to save a file and in
Brackets you know your file is unsaved
if there is a DOT next to the file name
so right here and right here so to save
your file all you have to do is command
s and that saved your file another
helpful shortcut is copy and paste so
first what you got to do is highlight
what you want to copy and then to copy
you use command C and then go to where
you want to paste whatever you copied
and to paste all you have to do is
command V you can also cut lines of Code
by highlighting what you want to cut and
then use command X and then go to
wherever you want to paste that code and
just do command V and you can also paste
what you just cut or copied in other
files now you'll notice that we have two
unsaved files so instead instead of
using command s in each file you can
save all the files at the same time with
command option s so now you'll notice
that there isn't the dot next to the
file names another helpful shortcut is
searching your file so let's say I had a
really big file with a lot of code in it
to search that file I could use the
shortcut command F and search whatever I
want to find
and it will highlight it for me and if
there's multiples you can see that I can
go through every occurrence of whatever
I want to search another helpful
shortcut is to replace words or
characters and that shortcut is command
option F and it will give me what I want
to replace and it will let me search up
anything just like command F and then I
could replace it with whatever so I
could replace every occurrence of the
number seven with that and then just go
through each one and it replaces every
seven with three A's you can also
replace things that aren't necessarily
in the file that you're editing so if I
wanted to replace the four here in file
one and and the fours in file two I
could use command option shift F and I
can replace four with hello
then it will show me every occurrence of
four in what files and then I could
check which ones I want to keep and
which ones I don't and then I could just
click replace and there you go and then
it replaces every four with hello
another helpful shortcut is if you have
a really long line and you're kind of
lazy to just use your mouse to do that a
much faster way to go to the ends of the
lines is to just use command and then
the arrow keys which is helpful if you
have a really small font size so it's
kind of hard to pinpoint the end of a
line so using command and then the arrow
keys is pretty helpful in the last
shortcut that I sometimes use is
highlighting lines without using my
mouse and all you have to do is use
shift and then you use the up or down
arrow keys
and that comes in handy every now and
then oh and some more shortcuts would be
to increase the font size with command
and then the plus sign or you can't
really tell here because it doesn't show
the plus sign but that's where the plus
sign is
so I could increase the font size or
decrease it with minus okay and this is
the last shortcut and sometimes I use it
but not really but it's just helpful to
know and that is to write on multiple
lines so let's say I wanted to write two
lines that were exactly the same or
pretty similar I can write them both
lines by pressing command and then I
could click on wherever I want to type
so now I could type on two different
lines so those are just the few
shortcuts that I use every now and then
or pretty often and I think they're
going to be really helpful and make you
a more efficient coder okay let's start
coding the first thing you want to do is
open up an internet browser
I recommend using Chrome
and then you want to go to replit
and when you first open up replit you'll
see a page that looks similar to this
you want to select JavaScript because
that's language that phaser uses
now for our first line of code let's
start off with console.log
console.log is primarily used for
debugging so you'll find it very useful
when you get stuck writing code
now between the parentheses let's just
say hello world
run the code
and it prints hello world to our console
now the shortcut that I just did instead
of clicking run was command enter so
with console.log you can print out
anything as long as it's in quotes
you can also type in numbers
false
of course true
no
and undefined
we'll be getting into these terms later
in the course but for now
congratulations believe it or not you
just wrote your first line of code now
let's learn about comments let's say we
have some code
and let's say we're having some trouble
figuring out what this code does we can
add a comment like this
comments are just comments that you
write on your code to make your code
easier to understand so notice to make a
comment you start off with
two forward slashes but this is only for
one line to make a multi-line comment
you would use this syntax forward slash
Asters asterisk forward slash and then
write your comments between the two
asterisks like so and now you have a
multi-line comment without having to
constantly write the double forward
slashes like this
so don't do this
right now commenting might seem useless
because we've only learned console.log
but Azure code becomes more complex
you'll find commenting to be very useful
it's especially useful when working in a
team environment or if you haven't
looked at your code in a while and
you're trying to figure out what your
code does commenting helps you
understand your code quicker and easier
so get in the habit of commenting your
code okay before we go on I'd like to
point out something that might confuse a
lot of beginners and that's spacing in
JavaScript
so right now you don't have to know what
all this means we'll get into all of
this in later videos the point I wanted
to illustrate was that spacing does not
matter as long as you're not dealing
with reserved words and by reserved
words I mean words like VAR
or function
and I just wanted to point out when I
run the code that all of our variables
work perfectly fine
same with our functions
however let's remove the space between
our reserved word and our function name
we can see that we already get an error
and the error that we're getting here
missing semicolon before a statement
doesn't really tell us what's wrong
because this is just the wrong Syntax
for making a function there has to be a
space between a reserved word and the
name same goes for a variable if we
remove that space we can see that the
colors changed the JavaScript engine
doesn't know that num5 is a variable so
we need to have a space here but you can
see here the space doesn't matter on the
sides of equal signs or math functions
or math operators but let's not get too
ahead because we're going to be learning
all about these in future videos so I
just wanted to point out that spacing
only matters when you're dealing with
reserved words like function or VAR and
there are a few other reserved words but
function in VAR are the two most common
now let's learn about math and
JavaScript for this video we're just
going to focus on our console in replit
so in JavaScript you can compute math
equations with different operators so
for addition you would just use the plus
sign subtraction the minus sign
multiplication with the asterisk
division with a forward slash and these
are your four main math operators
there's also modulus which is the
percent sign and modulus gives you the
remainder of one value being divided by
another value for for example nine
modulus two gives you one because two
goes into nine four times giving you
eight and that gave view a remainder of
one you can also use parentheses to do
math inside the parentheses before doing
the math outside of the parentheses for
example
so math and JavaScript just follows the
math order of operations you can also
add words with other words or words with
numbers for example
so you can see here if we add a word as
long as it's in quotes and add it with a
number JavaScript will add the number to
the word and of course you can add words
with other words
however you can't subtract words or
multiply words you can only add words
which is called concatenation so now you
know how to use the math operators in
JavaScript now we're going to learn
about the comparison operators
comparison operators return either true
or false and usually you would use
comparison operators in conjunction with
while Loops if statements else if
statements and a few other things but
for now we'll just focus on the
operators themselves so for example
equals equals is a comparison operator
and it checks for sameness so one equals
one that's true one is greater than one
one is less than one
is false
you can also do one is less than or
equal to one that's true there's also
greater than or greater than or equal to
there's also not equals so nine equals
nine that's true but nine not equals
nine which is the exclamation mark with
a equal sign
that's false and this will return False
only if the left side of the operator is
equal to the right side of the operator
we can also compare words so
that makes sense right there's also
another operator which looks like this
which is three equal signs instead of
two equal signs and the only difference
here is that this is the strict version
of equals to so for example one equals
one
that's true however
if we put one of the ones in quotes and
one one not in quotes it returns false
because the strict version of equals to
checks for data type and what that means
is well for this example this one is a
number
but this one is a string and a string is
like a word and words don't equal
numbers in JavaScript it's kind of
confusing right now but we'll learn
about data types in a later video but
for now congratulations you just learned
seven different comparison operators now
let's learn about variables you can
think of variables as people and these
people only have one job and that job is
to remember the last thing they were
told it's kind of hard to conceptualize
at first but it'll just make sense the
more you practice so to make a variable
you start off with VAR and then the
variable name
and then the value and then you end your
line with a semicolon now a semicolon is
just like a period at the end of a
sentence in JavaScript semicolons are
not necessary but they make your code
easier to read so I recommend using them
as often as you can so your variable can
have any name as long as it doesn't
start with a number believe it or not
one of the hardest parts of JavaScript
is naming your variables so here
variable name is not a good name for our
variable because it doesn't give us a
good representation of what our variable
means I think num makes more sense so
this variable is a number type its data
type is a number it can also have
decimal points
and it can also be negative as well the
next kind of variable is the Boolean
and that can either be true
or false booleans can be used for things
like if statements while loops and a few
other things which we'll get into a
later video the last kind of variable
we're going to learn is the string type
and a string is anything that's in
quotes a string can be empty like so and
of course it could have words in it
you can have spaces it can have
sentences it's just anything that's in
quotes and JavaScript just looks at this
like a sentence so if we run our code
nothing happens because we're not
console.logging anything now in our
console we don't have to write
console.log our console does it for us
so if we want to console.log num we just
type in Num and we can see here it
equals negative
123.0123 bull equals false and we can
see here it equals false and string
equals whatever this says we can also
add variables with other variables so we
can add string with num and we can see
here that JavaScript just concatenates
our number variable to our string we can
also reassign variables so right now
this is what num equals we can reassign
num to equal something else
like that and now we can see num equals
three four five same thing with Boolean
variables
and of course strings
now there's two more types of variables
I'd like to teach you and that would be
null
and undefined
so null an undefined mean kind of the
same thing basically null and undefined
mean their value is nothing the only
difference is when a variable is set to
null we are assigning it a value that is
a value that does not exist and you can
see here we're getting a warning because
this is redundant an undefined variable
is a variable that is just declared like
that so once again a null variable is
explicitly set to equal nothing an
undefined variable is just a variable
that hasn't been defined now let's learn
about arrays and objects an array is
like an empty folder
and this is what they look like
so this is our empty folder and with
arrays we can hold lists of information
and we separate each element with the
comma and it's good to space things out
so here
we see we have an array which has a
length of 5 or it has five elements and
arrays are useful because you can use
them like lists that hold similar
elements so what if we only want to get
one element from our array we would use
something called bracket notation
and that looks like this
so here we are using brackets to get the
first element of our array and that
returns one so when you want to get an
element at a specific index in an array
you would start from zero so let's say
we want the Fifth Element since we start
at zero we know that the fifth element
is at index four so zero one two three
four and we can see here we get five we
can also have arrays that have different
data types
like so and that's just because
JavaScript is a very flexible language
in languages like Java you would only
have arrays or array lists that can only
have a single data type but in
JavaScript you can see here that we can
have different data types in the same
array and of course we could also have
variables in our array
and objects
so this is an empty object objects are
very similar to arrays
except there are a few differences one
being it uses the curly brackets instead
of square brackets and when we put stuff
in objects we give each element a
property name so objects have properties
like so and the properties have values
so let's make a human object with me
and you can see here
that it's very similar to an array the
elements are separated with commas
but you can see that we're using curly
brackets where we have to name each
element with a property name or another
way you could think of this is that
objects have properties and properties
have values let's just run the code
and to get a specific property of an
object we would use something called dot
notation instead of bracket notation
so we can get
human.name and we can see it's equal to
Michael age 18. so you can see the
similarities between objects and arrays
but you can think of objects as as
things like objects and these objects
have different properties and so with
that in mind you can see that objects
can be useful for for storing character
information because with property names
it's easier to know which value is
assigned to what whereas in an array
each value is selected by its index now
let's learn about if else if and else
statements this is where booleans and
comparison operators come in handy so
this is the skeleton of an if statement
between these parentheses we put in a
Boolean value or something that returns
a Boolean value and between these
brackets is what our if statement does
so for now let's just have our if
statement console.log something
and let's make a variable called Boolean
and set it to true and then we can put
Bull in here run the code and we can see
here that something is printed out
that's because bull is true and because
wool is true our if statement runs the
code between its brackets if Bool were
false and we ran the code nothing would
happen because an if statement will only
run its code between its brackets if
this Boolean is true we can also use our
comparison operators and because one
does equal one this returns true and so
our line of code is ran and let's make
this equal false nothing happens so
let's say our Boolean value is false we
could use something called an else if
statement which looks like this and this
is just an if statement which the
previous if statement defaults to if
this if statement was false so here this
won't run because wool is false and then
we'll check for something else so we
could just say if 4 is greater than one
it's true and have this else statement
do something run the code and we can see
here this line of code is ran because
this was false so this if statement went
on to the next elsif statement and
because this is true it runs this line
of code now let's say this was false we
can use an else statement which is the
default statement for all if and else if
statements so this else statement will
run no matter what unless one of these
if or else if statements are true so
let's have this do something run the
code print out six because both this if
statement and this else if statement are
false so just defaults to the else
statement so one thing to know is that
if else if and else statements should be
ordered in specificity and what I mean
by that can be better illustrated by
this example so we have a variable
called num and it's equal to 10 and
let's change these if and else if
statements and run the code and we can
see here that only something is printed
out to our console but we wanted this to
because num is greater than six this is
what I meant by ordering your if and
else if statements in specificity so
let's change the order of these if and
else if statements and change our num
variable to something else and run the
code and let's change this so it's
easier to understand we can see here
that num is not greater than six so it
defaults to this elsif statement and it
prints out something to do instead of
something to do even though num is
greater than one so that's just
something to keep in mind when making
your if else if and else statements now
you know how if else if and else
statements work now let's go over while
and for Loops I'm first going to go over
what four Loops are because they will
make while Loops easier to understand so
to make a for Loop we start off with
four and then parentheses and between
the parentheses we start by declaring a
variable usually it's I and set it to
something and then we'll set a limit for
when to stop looping so in this case
we'll have I is less than 10. and then
we'll have something that increments our
variable which can be something like I
plus plus and let's just have
console.log
in our Loop and run the code so what
just happened well we first defined a
variable I and then we console.logged it
so that's why zero is printed out
because I starts off as zero and then it
Loops again but right after you finish
one Loop you increment your variable and
so that's why when this for Loop Loops a
second time I has been incremented by
one so that's why one is printed out and
then so on now you don't have to always
increment by one you could also
increment by two
mixer and one thing to point out is that
it will stop looping when I is less than
10. so once I is equal to 8 it's
incremented by two and at that point I
is equal to 10 so it's not less than 10
so it doesn't print out 10. so you just
saw me use I plus plus
I plus plus is the same thing as I
equals I plus 1. is there an i plus plus
version for incrementing by two no but
you can do I plus equals two and that's
the same thing as what we just had so
let's run the code and it does the same
thing because I plus equals 2 is the
same thing as I equals I Plus 2.
so that's how a for Loop works now for a
while loop the syntax is this and we'll
just have our while loop do something
for each time it loops and for this
example we'll have variable called I and
set it to zero
so this is very similar to our for Loop
when we run the code we get the same
output as our as the first time we ran
our for Loop first we're defining a
variable I and setting it to zero and
while I is less than 10 it will run this
code so first I is equal to 0 I is less
than 10. so it console.logs I which is
zero and then it increments it by one so
that's how we get 0 through 9 because
once I is equal to 9 it's incremented by
one so then it equals 10 which is not
less than 10 and so it just stops at 9.
so why would you want to use a while
loop well a while loop is useful for
when you don't know how many times
you're going to be looping for example
if you had something random so let's
change things up
foreign
so math.random produces a number between
0 and 1 including zero but not including
one so it will go from zero to zero
point nine nine nine nine nine Etc and
each time we loop we're reassigning I to
another random value so when we first
run our code it looped four times let's
run our code again it looped one time
again three times so you can see that a
while loop is useful for when you don't
know how many times you're going to be
looping and that's how while and for
loops work now let's learn about
iterating through arrays and objects so
here we have an array variable and an
object variable let's iterate through
the array variable first so we can just
use a for Loop
so one thing to note is that all arrays
have a property called length and length
is just the amount of elements in the
array so let's run the code and it
prints out each element of our array we
can also use a for each Loop which looks
something like this
and we get the same effect now a for
each Loop is a little complicated
because it uses something called a
callback function and what the for each
Loop does for an array is it takes each
element and we're assigning it to I and
then we are console.loggingi in our case
and of course you could do a bunch of
other things like incrementing I by one
but we'll learn more about functions in
a later video now to iterate through an
object we can't use a for Loop because
if we try to
you'll notice that we'll get stuck
and just writing it out you can already
tell that we cannot get an index zero of
object because we don't have indexes in
objects we only have properties so
instead of a for Loop to iterate through
an object we would use a four in Loop
like this
we can see that it prints out each
property name of our object now what if
we want to print out the property values
well we would just take our variable and
use bracket notation and put an i and
run the code and we can see that each
property value is being printed out
so one thing that I didn't mention in my
arrays and objects video is that you
could use bracket notation to get the
property value of an object so just to
clear things up we have an object
variable called object and here are its
properties and values we can use bracket
notation but we have to put the property
name in quotes So
P1 and that gives us one however if it's
not in quotes we'll get an error so make
sure if you want to use bracket notation
when getting the property values of
objects that you put in the property
names in quotes but I prefer just using
dot notation because it takes up less
space so that's how you iterate through
arrays and objects now let's learn about
functions and methods a function is
basically a block of code that does
something so to make a function we start
off by typing in function and then a
function name parentheses and then curly
brackets so instead of function name
let's call our function add and between
the two parentheses is where you put in
the arguments for your function so let's
have a and b be our add functions
arguments and then our function will
just return the sum of a plus b so when
we run our code nothing happens because
we haven't called our function yet the
color function we can either just do it
in our console like so or we get assign
line it to a variable
and we can see here that num is equal to
16. so what's happening here well when
we call our function which is when we
type in our function name followed by
parentheses we are saying let's use the
add function which takes two arguments
and then in this case our add function
just Returns the sum of our two
arguments so eight and eight will be the
equivalent of A and B in our add
function and our add function just
returned 16. now if we don't have the
correct amount of arguments and we run
the code we get not a number because we
only have one argument and our add
function is looking for a second
argument called B but you can see here
we only have one same thing would happen
if we have no arguments where our add
function is looking for argument a and
argument B but here we haven't defined
them now if we don't have parentheses we
are just saying that num is the function
so when we run our code we can see that
num is a function and we can call num
like so
let's make a more complex function first
let's make an array
and let's have a function called
iterate
and it takes an array argument and then
it will console.log before
and after
and what we are going to do with this
array is change each value
foreign
function down here
and run our code to make things more
clear let's just rename this variable
Bob and run our code so we have a
variable called Bob which is an array
and then we are calling the iterate
function on Bob so our first argument
will be referred to as array or ARR in
our iterate function so at first
console.logs array which in our case is
just our Bob variable and then it
iterates through each value from our Bob
array and adds 10 to each element and
then after it's changed each value in
our array it will just console.log after
and our array after we've changed it so
function arguments can be confusing
because of the names of the arguments
the names of the arguments are just for
the function to handle we don't need to
have a variable called array so that we
can call our iterate function you can
see here that we just have a variable
called Bob and then once we call the
iterate function the iterate function
will just refer to this argument as
array and then so so this function will
just do whatever it does with array now
a method is just a function of an object
so let's make an object
and let's give it a run property which
is a function
and this function inside of our human
object just console.logs running run our
code and we could see that human dot run
is a function and when we call human.run
it prints out running so a method is
just a function that's part of an object
and that's how functions and methods
work here's one thing that I'd like to
point out about functions so let's say
we have a function called hello and it
takes a number
and it has a bunch of if statements
like this
let's run our code and then call our
hello function
and we can see here we're only getting
one return value and that's just numb
even though we are also returning or we
should be returning num times two and
num times three because all of these if
statements are true so the point that
I'm trying to illustrate here is that
once you return something in your
function your function stops executing
so here we can see num is greater than
10 so it will return just num and the
function will stop executing all of this
code does not matter once something has
been returned let's make another
function called greater than and this
function takes two variables let's add
in some if statements
let's run our code and let's just check
to make sure if our two arguments are
equal we get equal if our first argument
is greater than the second argument we
get true and we get false if it's the
other way around so first let me point
out that if your if statement only has
one line then the curly brackets are not
necessary so this if statement right
here is the same as
this but I'd also like to focus on this
else statement this else statement is
unnecessary because we already know that
if a is less than b then we should be
returning false so we can just remove
this else statement
run our code
and we get the same results one last
thing I'd like to talk about functions
and methods is scope and you can think
of scope as as where a variable can be
used so to demonstrate scope let's make
a function called hello
and Insider function we're going to be
declaring a variable called num and
setting it to a number and then let's
console.log num and run our code let's
call our function hello
so we can see here that it just prints
out the value of num however in this
case because we declared num with VAR
inside our hello function we can only
use num inside the hello function so if
we try to print out num num is not
defined if we Define a variable called
num
and run our code we can see that here
num is equal to six if we call our
function
their num is equal to 234 but if we
pronounce num again we can see that it's
still equal to six that's because num
inside of hello is a local variable and
if we declare a variable outside of our
function it's a global variable so we
have a global variable called num but
that num is different from this num
scope is just something to keep in mind
when you're making variables and
functions so now you know how to use
functions and methods but you also know
how to stop functions from executing
using return and also about scope now
we're going to be learning about the
developer tools or Dev tools so in
Chrome to open up your Dev tools right
click and then click inspect
you can also just use command option I
and we can see here we have a bunch of
tabs that tell us everything about our
internet browser and the web page that
we're on but we'll just focus on Console
console does the exact same thing as
replit the only difference is is that
you don't need an internet connection to
use our devtools console but also we
don't have the split screen that replit
has which I like but it does the exact
same thing that replit does however if
you want to return to a new line we
can't click enter we have to do shift
enter
so when we are debugging our code we
won't be using replit we'll be using our
Dev tools now we're going to be learning
about regular expressions for this make
sure you're on rubular.com it says Ruby
regular Expressions right here but it
also works for JavaScript regular
expressions are used for searching a
string for a specific pattern so for
example let's type in a string here
and in our regular expression we can
type in a word that we're looking for so
here we can see that Michael is being
returned and at the bottom we can see
all the different regex selectors so
let's say I wanted to search a string
for three consecutive numbers so let's
just type in a bunch of stuff and for
our regular expression we would put
backslash D and we can already see that
we're getting every digit in our string
and if we want exactly three in a row we
would just do something like that that's
the gist of regular Expressions as you
can see there are a lot of options for
regular Expressions but this is
essentially how regular Expressions work
so let's translate this over to
JavaScript let's make a variable string
and just put in a bunch of stuff and run
our code to use regular expressions in
JavaScript the two most commonly used
methods are match
and test so to use test we start off
with a regular expression and then put a
dot and then we're calling our test
method and between the parentheses let's
put our string run our code and we can
see that we get true so test returns a
Boolean and it returns true because we
have a JK in our string we can also use
match except instead of putting the
regular expression or regex first we
would put in the string Dot and then
match and then in the parentheses we
would put our regex so something like
that run a code and we can see here that
we have JK in our string right here as
well as the index or the location of it
and the input that we invoked the match
method on now what if we have multiple
jks in our string
run our code
and run the same function we can see
here that we're only getting one JK what
if we want to get all of the jks in our
string well we can just add a g outside
of the two forward slashes run the code
and you can see that we get a list of
every JK in our string now what the G
stands for is global so it will search
everywhere in the string the G is what
you would refer to as a modifier now
there's a bunch of other modifiers but I
find that g is the most commonly used so
another good website for regular
Expressions is regex101.com and this is
similar to rubular except you can see
that the interface is a little more
complex but it gives you a list of all
of the modifiers that you can use and
that's how regular Expressions work now
let's learn about map reduce and filter
map reduce and filter are used for
modifying arrays let's start off with
learning how to use map first we need to
make an array
now that we have our array let's call
the map method on it
the argument we're going to put in for
our map function will be an anonymous
function and what an anonymous function
is is just a function without a name
like so in this case this function is
also called a callback function because
we are using this map method on our
array and what map does is it uses this
function which we are about to make and
it will invoke this function on each
element in our array so for our function
we'll have one argument and in this case
this argument will be the value of an
element in our array and what map does
is it changes each value in an array so
we have to return something in our case
let's return I or the value in our array
plus five and run our function and we
can see that our map method returns a
different array which is the same thing
as our array except each element is
incremented by five but if we print out
array we can see that it's still what it
was before we call the map so to
reassign the array value we would just
do something like this where we are
saying array is now equal to array with
the map method invoked on it so let's
run our code and we can see now that
array
has been changed now let's learn about
the reduce method so let's just switch
out map for reduce now the anonymous
function in our reduce method often
takes two arguments and those are A and
B so a is the current value and B is the
next value that you're going to add on
to a so let's just return a plus b run
our code and we can see that array has
been reduced to 28 because if you add
all of these numbers it will equal 28.
lastly let's learn about filter so let's
replace reduce with filter and for our
Anonymous function we'll go back to just
having one argument and we will be
returning a Boolean so if we return true
we will keep the value in the array and
if it's false we will not include it in
the new array so let's just say if I is
greater than 5 and run filter so we can
see here that array has been filtered so
that only elements greater than five are
included and those are the basics of
using map reduce and filter now let's
learn about the the this keyword and
what this can be used for so this is a
very tricky concept this refers to the
current context of where we're writing
this so right now if we just type in
this we get the window object however
you cannot assign the this keyword to
anything this simply refers to the
context that it's in so let's make an
object
and let's give it a function called high
and high will just return this so let's
run our code and call the object dot
High function and and it Returns the
object obj so to better illustrate this
point let's add some more properties run
our code and let's call the same
function
so you can see here that when we call
the high function this refers to the
object that this is in and this is in
the object variable I think a more
practical use for this would be to make
a Constructor function and a Constructor
function just makes an object
so here we have a Constructor function
and it creates a new object
and to make a new object we can just set
it to a variable
we would use new and then call the
function
let's run our code
and we can see that Bob is now equal to
an object now it's very important that
we use the new keyword because that lets
JavaScript know that we are trying to
make a new instance of an object so
without using new
Bob is still undefined because our human
function doesn't return anything so
again the new keyword is important
so that it lets JavaScript know that
we're trying to make a new instance of
an object now I'm going to go over some
tips and tricks in JavaScript which you
might find pretty useful in certain
situations the first thing I want to
talk about is using quotes within quotes
so let's say I have a string
and we're not getting any errors so
that's good but what if I want to say
I'm going to the park
and you can see already that we get an
error because to JavaScript this doesn't
make sense because it's like we have our
own string right here due to the single
quotes here and here so there are two
ways to fix this problem the first way
is to use the backslash and the
backslash is known as the Escape
character because it allows you to use a
single quote between two other single
quotes and when we run our code we don't
get any errors and the backslash quote
is just a representation for one quote
another way you can fix this problem is
to use double quotes and to just have a
single quote inside and when we run our
code we get the same output and so with
that in mind you could also use a double
quote inside single quotes like so
the next trick is the ternary operator
so let's make a variable called number
and then you want to have a Boolean or
something that returns a Boolean and
then a question mark
and then the value if the Boolean is
true
colon and then a value if the Boolean is
false
and we can see that number is equal to
one two three because this returns true
because it's true we are setting number
to one two three
If This Were false
it's now five six seven because this is
false and so our ternary operator
defaults to the second value that we
State let's go back to the string that I
had at first
so we know we can get the length of an
array
like so
but we can also get the length of a
string
and that Returns the amount of
characters in a string and that includes
quotes and spaces another cool thing you
could do with strings is bracket
notation so if I wanted to get the first
letter I could use bracket zero and the
second character I could just use
bracket one so it behaves very similarly
to an array and the last two tricks I'm
going to talk about are related to
objects
so let's just make a
object
so here we have a variable called human
and it has a property called name and
its value is Alex property called age
and its value is 23 and it has a
property of sports and it's an array of
three different Sports golf basketball
and football so one cool thing you could
do in JavaScript is ADD properties to an
object
without having to do them while you
declare the objects so you don't have to
do
something like this we can actually just
use our object variable so human and
then the property that we want to add
and then we could set it a value like so
and when we print out human we can see
that we just added the property called
property and its values one two three
without having to add it here
the last trick is related to
Constructors so let's make a Constructor
and create a new instance of human
you can see here that we have a new
variable called Bob and it's an object
with two properties now what if we want
to add another property to our
Constructor without having to modify the
Constructor here we can use the
Prototype object so for example human
dot prototype dot run and we could make
a new function or a new method
and now we have a run function as a
property for our human Constructor so
now Bob has a run method and when we run
it
we can see that run is actually a method
of human
so these are just a few tricks and tips
in JavaScript they're a lot more so
these were just a few to get you started
after you've checked out code Wars
coderbyte and free code camp and you
have a good understanding of how
JavaScript works you can start learning
how to make games with phaser so the
first thing you want to do is download a
text editor and the one that we're going
to be using is brackets so just go to
brackets.io and just follow the
instructions for downloading it next you
want to go to phaser.io download
download phaser from GitHub even though
it doesn't actually bring you to GitHub
and download the min.js file the
phaser.min.js file includes everything
that you'll need to create a phaser game
but the file has been minified so it's
smaller next you want to create a folder
and let's just call it phaser demo
and in that folder you want to create
another folder called phaser and then
you want to drag your phaser.min.js file
into that phaser folder that we just
made next you want to open up brackets
and it will first show you this code of
how brackets works the main reason why I
like brackets is because of the live
preview button it creates a local server
and it shows the updates from your code
in real time but it only updates HTML
and CSS in real time so because we're
going to be making games with JavaScript
we're going to have to reload the page
every time we save our code but the
local server is what we really want next
you want to open up a folder and open up
the phaser demo folder and in our folder
we want to create a
index.html file and we have to create
the skeleton of a basic web page
and this is what it looks like we can
click our live preview button and it
will show us the webpage that we just
made which is empty right now we can add
elements to our web page by adding tags
so this is a header tag and I could add
content to the tag
but most of the tags we'll be using are
just script tags so other tags are out
of the scope of this lesson next you
want to create a main.js file and in
that file type VAR game equals new
phaser Dot Game parentheses and then the
width of our game the height of our game
and the renderer for our game which is
either webgl or canvas but you can just
put down phaser.auto which picks the
renderer for you next create a state one
dot JS file and this file will be the
file that represents the first date of
our game a game state is like a scene in
your game it could be menu state or high
score state or game over state or game
state but let's just call this state
state one so in our first date we have
to create a object variable and just
name that object the name of your game
so in our case let's just name it demo
and set it to an empty object next we
want to add a state 1 property to our
demo object and make it a function and
then finally we want to type demo dot
state1 dot prototype and set it to an
object that has three functions inside
of it and those functions are preload
make sure to separate them with commas
create
and update
let's go back to our main.js file and
add a state to our game and we do that
by typing game dot state DOT add
parentheses the name of our state or the
key to our state and then the name of
the property in our demo object so we've
just added a state to our game now we
have to start the state and this will be
the first state that will be ran when
our game first loads so let's type game
dot state DOT start parentheses and the
key of our state which is State one
let's go back to our index.html file and
now we have to add script tags which
basically load scripts into your web
page
so to add a script tag we just say
script
and we add a source attribute to our
script tag and for our first script tag
we'll load the phaser
dot Min dot JS file because we put
phaser.min.js in our phaser folder we
have to say the name of the folder first
and then phaser.min.js this is the path
of where our phaser.min.js file is so
this is what our script tags will look
like we start off with an opening tag
and a closing tag make sure
phaser.min.js is the first script that
you load into your web page next we'll
add another script tag and set the
source to our state1 file
and finally in our body tags we'll load
our main.js file
and then save everything you can do so
with command s which saves the file that
you're currently editing or command
option s which saves all the files and
you can see here that we have a black
screen this is a screen for our game if
we open up our developer tools which you
can do so with command option I or right
click and inspect we can see that our
black screen is a canvas element what
you just wrote was the boilerplate for
any phaser game and as of right now our
game is just a blank screen right now
our code is saved locally on our
computer but what if our computer breaks
or we want to work on a code on a
different computer we can save our code
online and the most popular way to do so
is through GitHub so go to github.com
and make a GitHub account after you've
made an account click new repository a
repository is like a cabinet that holds
all the files to a certain project so
let's just name our repository phaser
demo and create repository next we have
to open up our terminal you can do so by
using the shortcut command spacebar and
just type in terminal you can also use
item item and terminal do the same thing
so it doesn't matter which so it doesn't
matter which one you use so to save our
code we have to go to the correct
directory if we want to know which
directory we're in we use the command
PWD or print working directory you can
think of directories as locations in
your computer so right now I'm at my
root directory but I want to be in the
phaser demo directory we can do so by
using the CD command or change directory
desktop
slash phaser demo and capitalization
doesn't matter
and now when we print out our working
directory you can see that we are in the
correct directory now we have to link
our directory to our repository on
GitHub and we can do so with the
following commands git init git add dash
dash all
this will add all of our files to our
commit
our commit is made on the next command
which is git commit Dash m
and just say
first
commit a commit is like a screenshot git
add dash dash all adds all of our files
to this screenshot and then we can push
our screenshot to GitHub so run this
command and then copy this command on
GitHub
which sets the origin for our remote and
then use this command to push all of our
to push our commit to our Repository
your terminal might prompt you for your
GitHub username and password so just
enter those and you should be able to
push your commit to our GitHub
repository so now if we go back to
GitHub and we refresh the page you can
see that our code has successfully been
pushed to our repository okay before we
start writing more code it's important
to understand how phaser games work so
if you go to phaser.io click examples
and it will give you a list of pretty
much everything you can do with phaser
so let's just go down to input let's
check out
uh this example
so in this example I can move right or
left depending on which arrow key I
press and Below you can see the source
code to the example
so because the author of this code only
has one game State the author doesn't
have to say
game.sate.adgame.state.start this is the
equivalent of those two lines but what I
want to focus on are the preload
create and update functions there's also
a render function but that does roughly
about the same thing as the update
function so we won't be using that for
this lesson so let's go back to the
preload function
the preload function is primarily used
for loading images so so here we can see
the authors loading a ground image a
river image Sky image
Etc a Sprite sheet is a collection of
images and a choose for animation we'll
get into what all this stuff means in a
later video because I just want to focus
on the preload create and update
functions so the preload function is
only called once and that's at the
beginning of your game State and it's
primarily used for loading images the
create function is similar to the
preload function except the create
function is used for setting the initial
values for everything in your game state
so here we can see the author is adding
the background images and because you
only need to add the background images
once you put it in your create function
and here we're adding more images and
this line right here has the game camera
follow the UFO Sprite but again we'll
get into what all this code means in
later videos the update function updates
the frame of your game it updates the
frame of your game roughly 60 times a
second depending on the performance of
your code so going back to the example
our update function is being called
right now and my right or left arrow
keys aren't pressed down as soon as I
press down a narrow key the update
function will check that yes the right
arrow key is being pressed down and it
will invoke these properties on the UFO
Sprite so each fret so each frame in the
game is a still image so for example
this could be frame 1 Frame 2 frame 3
frame 4 frame five and when you run
those frames 60 times a second it
creates the illusion of motion that is
essentially how phaser games work now
that we have one state let's add
multiple States we can start by making
another JS file let's call it state2.js
and we can copy all this code except for
VAR demo equals an empty object because
we only have to make a game object once
and just paste it into state2.js and now
we have to replace State 1 with state
two but instead of replacing one with
two manually by just typing it out we
can use the shortcut command option F
and that will replace the specified word
with the word you want to replace it
with so here I'm specifying State 1 and
I want to replace it with state 2.
replace
command option f is especially useful
when you have to replace a lot of words
with the same word now let's go to
main.js
and just copy this line and again
replace date 1 with state two
add another state script make sure you
have the right file name and save
everything and you can save all the
files with the shortcut command option s
now now if we restart our code we have
two game states to switch States we can
use the same method game dot state DOT
start and use the key of the state as
your argument run the code and now we're
in state two but how can we
differentiate between states let's go
back to our state files and change the
background color we can do so in our
create function so type out game dot
stage dot background color and you have
to set it to a hex color like hashtag
ddddddd saver code restart our local
server and now we can see that state 1
has the color of this hex color now a
hex color is basically a combination of
red green and blue if you Google Hex
Color Picker and click the first link
you can pick any color you want and it
will give you the hex color for that
corresponding color so the first two
characters represent red the third and
fourth color represent green and the
last two colors represent blue so let's
make state two have a green background
I'll just copy this hex code and in
state 2 I'll type game.stage dot
background color equals that hex code
and make sure it's in quotes save our
code restart our local server so right
now we are in state 1 to switch States
we can type game dot state DOT start
parentheses and type in the key of your
state as the argument so I'll just type
in state 2.
and now we are in state two let's also
add a console.log to tell us which state
that we're in save our code restart our
local server and now we can see when
State 1 first starts at console.log
State one if we switch States
we can see that state 2 has been
console.logged so now let's just add
eight more States states zero through
nine
and let's just copy the code from State
2. and paste it and paste it in all the
files that we just made
and now we have to refactor the code
and now we have 10 states let's save all
our code don't forget don't forget to
load your script tags
and you also have to add the states in
your main.js file
save all of our code refresh our local
server and now I can switch between
States but for some weird reason
sometimes you have to click the canvas
element or the game screen for your game
to start running and here we can see
that our states are working because
they're console.logging what state they
are so right now we have 10 states but
our only means of switching between
states is to go to our developer tools
and typing out the
game.state.start command something like
that so instead of having to go to our
console and running that command we can
make an event listener so we can just
press the number zero through nine and
when we do so phaser will bring us to
that state so first I think we should
start with State Zero Save Our code
refresh our local server and we get an
error no State found with the key state
0.
the error here is that I forgot to load
my state 0.js file refresh and we get
another error so this time our console
tells us that our error is in state 0.js
and it's on line one so let's go to
State 0.js and it says demo is not
defined well that makes sense because we
Define it later in state one so let's
just cut this line of code save that
file and paste it in state 0. save it
refresh your local server and now we get
no errors and here we can tell that we
are starting at State 0 because State 0
console.logs State 0 when it first
starts so when you're developing games
with phaser make sure to have your
developer tools open because the console
is where you'll get the error messages
now let's add an event listener so in
our create function we can say game dot
input.keyboard dot add key and here is
where you put the key code so each key
on your keyboard has a specific key code
phaser makes it easy so you don't have
to remember the key code for each key on
your keyboard you can just type phaser
dot keyboard Dot and then the name of
your key so if I wanted to get the key
code of a I could type in
phaser.keyboard.a key code 65 but I want
the key code for one so I would just
type in one and that gives me 49. so
instead of typing out 49 I think it
makes more sense to just type out
phaser.keyboard.1 because that way
you'll know that this event listener is
for the one key instead of writing 49
which you would have to remember that it
represents one next we want to say on
down DOT add parentheses the name of the
function change state which we haven't
made yet null null and then the argument
which will be the arguments passed to
this function which is a callback
function in this case the second and
third argument are the listener contexts
and the priority which you can read more
about in the phaser documentation so
let's make a function change state
and this function takes a state number
or state num and all this function does
is it starts a new state
our code refresh our local server
actually it's lowercase k re and the
argument here should be one actually so
when we press on the one key phaser will
call the change State function and it
will pass one as the argument save our
code refresh our local server and when I
press one we get an error and that's
because phaser has this weird thing
where the Callback functions are called
with another argument and that's like
the event object so it carries all the
information of what just happened so we
have to have another parameter and let's
just console.log what the first argument
is refresh our local server let's press
one and we switch States and we could
tell because it says State one and C dot
key is the first argument and it has a
bunch of information of what key you
pressed how long you press it for ETC
it's kind of useless in my opinion
because we have the phaser framework
doing a lot of the work for us but this
might have certain applications so now
we have an event listener so when we
press one we switch to State one so now
let's add another event listener
and let's have it for our key two
refresh our code and if I want to go to
state 2 I press 2 it brings me to state
two however if I press 1 I don't go back
to State one that's because event
listeners in phaser are local to the
state that they were made in so if I
wanted to switch States when I'm not in
state 0 I would have to add an event
listener in that state so let's just
copy this code and let's paste it in
state1.js
refresh our local server actually let's
have this be for the zero key and pass
it zero as its argument save our code
and let's copy and paste this into State
One
save our code refresh our local server
and now I can switch between State 1 and
state 0. so keep in mind that event
listeners are local to the state that
they were made in meaning that they only
apply in that state but functions are
Global as long as you declare them this
way
and not declaring them inside of your
state object so this is kind of
repetitive instead of having to write an
event listener for each key in each
state let's make a function that will
add all of the event listeners for Keys
0 through 9 and run that function in
each state but before that let's make a
function called add key callback and it
will take the key or the key that you
press down the function that will be
called and the arguments that will be
passed to that function and then we
could just copy and paste this line of
code
put it there replace this with key and
replace that with args and replace this
with
function don't forget to indent your
code it makes your code easier to read
so let's call our add key callback
function in our create function our
first argument is the key so let's say
phaser dot keyboard dot zero the
function will be change State and our
argument will be zero and we can delete
this line of code
saver code refresh our local server and
getting another error oh this time
keyboard is capitalized save our code
refresh our local server and let's
switch to State One
and if I press zero we go back to state
0. so now we have a function add key
callback that adds an event listener to
whatever key you specify it so let's add
an event listener for Keys 0 through
9.
save our code refresh our local server
and now I'm going to press 8 and now I
am in state 8. so remember event
listeners are local to the state that
they were made in so let's make a
function that will add the event
listeners and we'll call that function
in each state so let's call that
function add change State event
listeners it takes no arguments and
let's just cut and paste that code in
here and just call our function that we
just made
save our code refresh our local server
I'm going to press 4 I'm in state four
so now let's call this function in each
state
save all of our code refresh our local
server and actually I'm going to delete
that console.log here because
we don't need it and now I can switch
between each state by just pressing the
keys I think now's a good time to change
the background color of each state so
it's even easier to tell which state
you're in
foreign
refresh and now we can tell which states
that we're in so State 0 could be like
your loading state state one could be
your menu state
two could be like your game State a
level one state three could be level two
you know a state is basically a scene in
your game so now I think it's a good
time to push our code to GitHub
remember to change to the correct
directory
let's go back to GitHub
and there we go now all of our code is
up to date on GitHub now that we've
written a lot of code it's a good time
to push our code to GitHub so open up
your terminal or item
let's change directories to phaser demo
and because the folders on our desktop
we first have to say desktop
and then forward slash and then phaser
demo and if we print out the working
directory we can see that we are now at
phaser demo to go back to your root
directory you can just type CD
and it brings you back to your root
directory now let's say we were at our
desktop directory
like so
to go to our phaser demo directory
because we're already on our desktop we
can just type CD phaser demo and now we
are at the correct directory so because
we already set up a git repo on our
computer and on GitHub we don't have to
link our repository in our Command and
actually we can just do the following
commands to push our code to our repo so
let's start off with Git add dash dash
all that adds all our files to our
commit git commit Dash M and M stands
for message so let's add a message
enter
now we can just do get push
and if we go to GitHub and refresh the
page we can see now that we have pushed
all of our code to our GitHub repository
part of having a fun game is having a
game that can be played on all screen
sizes so if you notice when I resize the
window our game screen does not resize
we can use something in phaser called
the scale manager to fix this issue so
if we go to state 0 and just type game
dot scale dot scale mode equals phaser
dot scale manager dot show underscore
all saver code refresh our local server
and now we can see that our game will
resize depending on the size of our
window another thing to keep in mind
another thing to notice is that when you
set the scale mode of your game that
carries on to all of your other states
so right now we are in state 0 and you
can see that it resizes if we switch to
State 5 it also resizes now's a good
time to make our game world bigger and
I'll explain why in a few moments so if
we go to main.js let's make our game
world bigger and let's make it 1500 by a
thousand save our code refresh our local
server and it looks pretty similar right
the reason why we want to have a big
game world is that it will make our
images crisper or less or less blurry so
if you can imagine the actual size of
our game World should be about this big
but because we are shrinking it down it
will reduce the blur of our images so
the scale mode that we used was show all
but there's also four other scale modes
exact fit no scale resize and user scale
you can play around with the scale modes
on this line if you want to see how they
behave but I think show all is the one
you'll like the most so that's how to
use phasers scale manager you may have
noticed that after setting our scale
mode to show all we have this annoying
horizontal scroll in our window and
that's because there's this strip of
space called the margin and I won't go
too much in detail but margin represents
space on a web page so here you can see
that we have a margin of 8 pixels so to
fix this we can add a CSS file so make a
new file and call it main.css and now we
have to link our CSS file file in our
index.html file so to do so we have to
use a link tag and this tag doesn't
require a closing tag but it does
require two attributes and those are Rel
or relationship and this attribute tells
the index.html file that this is a style
sheet or it's going to be a CSS file and
now we have to link our CSS file with a
href attribute not say main.css and now
we're linking our main.css file to this
web page so let's go to our main.css
file and we have to select something on
our web page so we can just select
everything with the asterisk and then
add curly brackets and between the curly
brackets will be the CSS that we'll be
applying to our select and in this case
our selector selects everything
selectors are out of the scope for this
lesson but just Google CSS selectors if
you'd like to learn more so remember
that this white space is 8 pixels of
margin so to remove it we can just say
margin colon zero and end it with a
semicolon save our code refresh your
local server forgot to save our
index.html file refresh and now we can
see that we have no margin and when I
scroll I don't have a scroll bar at the
bottom of my screen so now let's just
push our code to GitHub
and there we go you just pushed our code
now we're going to start adding images
to our game but before that we need to
make our images two of the best free
resources for making images are piscal
and sketch pad so to start let's go to
piscalapp.com login and just click
create piscal here you can draw 8-bit
images very easily because of the grid
system that they have you can pick from
an array of colors and you can also make
your own custom color palette
you can also undo the last lines that
you drew with command Z or redo them
with command shift Z this button rotates
your images this one flips your images
they also have different tools for
making rectangles circles filling in
your shapes and you can also make Sprite
sheets which are useful for animation
but we'll get into Sprite sheets later
so there are a lot of features in piscal
and I won't be going over them so just
go to piscalapp.com and start creating
images and when you're done with your
image you can save it on the website and
click save gallery or you can export
them and download them onto your
computer by downloading the PNG the next
website is sketch.io once you're on
sketch.io click sketchpad and this
website is used for making more organic
images or smoother images so there are
different riding heads and again you can
change the color and undo all your lines
or redo all your lines with command Z
and command shift Z and again there are
a lot of features on this website that I
won't be going over so just go to
sketch.io and just play around with it
and when you're done with your drawing
just click export and make sure to set
your format to PNG and just click
download
now we're going to start adding images
and functionality to each state in our
project we'll start off with State 0.
the end result will look like this okay
here's state zero it's basically just a
guy who can move around the screen with
the arrow keys things to take note of
are that he animates while he walks and
that our camera has a dead zone so the
camera will only follow our character
when he's at this point on the screen or
if he's at this point of the screen
otherwise if he's between those two
points then the camera doesn't follow
him you'll also notice that he animates
as he walks and he stops animating when
he's not walking and he can also collide
with the top of the road
as well as the bottom of the road and
the sides of our background
so that's state zero so first you want
to go to piscal and make an image this
is one I made earlier he's like a fatter
version of Zelda and I named him Adam
but that's not important but when you're
finished making your image you want to
resize it so right now our image is only
26 by 50 pixels that's really small when
compared to the size of our game World
our game world is 1500 by a thousand
pixels so if we were to put this image
in our game we would have to scale it up
and it would be very blurry so with that
being said I'm going to make my image 10
times bigger and make sure to have these
two boxes checked when you resize your
image so I'll click resize and now my
image has been increased in size when
you're finished making your image you
want to save it to your gallery
and then you want to export it as a PNG
now we have to add our image to our game
so first we'll open up our phaser demo
folder create another folder called
assets
and assets are the images and sounds
that make up your game in our assets
folder we want to make another folder
and let's call this Sprites now we have
to drag our file into our Sprites folder
so make a new finder window with command
n click downloads there's our file let's
just drag it into our Sprites folder now
let's go back to brackets and here we
can see we have an assets folder in our
assets folder we have a Sprites folder
and there is our atom.png so you'll
notice there's this invisible box around
our image this can be problematic for
several reasons so to remove this white
space
let's go back to where our images in our
folders double click it and now when I
highlight it we can see the invisible
box so let's just highlight the part of
the picture that we want
and click command K that crops our image
so now when I highlight my image we can
see that the excess invisible space has
been cropped out let's save our file
with command s close this
and now we can see that we have removed
the invisible box and now we're ready to
add our image to our game so let's go to
State 0.js and in our preload function
we can load our image we can do so with
game dot load dot image parentheses our
first argument will be the key for our
image so let's name our image atom and
our second argument will be the path of
where our image is so our image is in
assets forward slash Sprites forward
slash and then we find our atom.png file
now that we've loaded our image let's go
to our create function and say game dot
add dot Sprite parentheses and our first
argument is the X position so the width
of our game world is 1500 and let's
divide that by two to get the center of
our width and our height is 1000 divide
that by two and our second argument will
be our key for our image let's save our
code refresh our local server and
there's our image let's change the
background so it's easier to see his hat
that's better you'll notice that our
image isn't actually in the center of
our game that's because images are drawn
from the top left corner also it's
important to know that the origin of our
game or the zero zero coordinate of our
game is in this corner so if we draw our
image at zero zero saver code refresh
our local server we can see that our
image is drawn in the top left corner so
let's draw our image back in the center
of our game and we're probably going to
be using the center of our game multiple
times so let's create a variable that
represents the sound width and Center
height of our game world
let's replace these with
Center X and Center y
save our code refresh our local server
and there we go a JavaScript tip here is
instead of typing out VAR to declare
each variable we can separate our
variables and their values with commas
like so so this line right here is the
equivalent of these three lines so to
manipulate our Sprite Which is just
another word for an image in our game we
have to set our Sprite to a variable and
let's just call him atom and assign them
dot Sprite now we can say atom dot
anchor dot x equals 0.5 save our code
refresh and now we can see that atom is
being drawn from the center of his image
and we can do the same for y
save refresh there we go we can also
write this in one line with the set to
method
the first argument is X and the second
argument is y save refresh your code
there we go now let's add some
functionality to our code by being able
to move atom with the arrow keys so if
we go back to phaser this is the example
that we looked at earlier we can use the
same implementation of if statements to
change the position of our Sprite so pay
attention to these two if statements
this one checks if the left arrow is
down and this one checks if the right
arrow is down when the left arrow is
down we are subtracting from the Sprites
X position
and when the right arrow is down we are
adding to the Sprites X position so
let's go back to brackets and in our
update function we'll use similar if
statements
so if gain dot input dot keyboard dot is
down
parentheses and our argument will be
phaser dot keyboard dot right and
remember this represents a key code we
will change the X position of atom and
add 4 to it save our code refresh and
when I press my right arrow key we get
an error and it says atom is not defined
and this is relating to scope because we
declared our atom variable inside our
create function we only have access to
the atom variable inside this block of
code so let's delete VAR and declare
atom up here saver code refresh and when
I press my right arrow key we can see
that atom is moving so let's change 4 to
a speed variable and we'll create our
speed variable up here and now let's
make an elsif statement if we press the
left Arrow key we also have to change
the plus to a minus so we move in the
opposite direction save our code refresh
and now I can use the left Arrow key
let's do the same if and else if
statements for vertical movement except
we'll replace a few letters so let's
make this up down and change X to Y save
my code refresh and when I press the up
Arrow key I go down because remember our
origin is up here in the top left corner
so when we add to our y position we're
actually going down so let's switch this
plus sign for subtraction and the
subtraction for plus saver code refresh
and now I can move in all directions
we'll continue State 0 in the next
lesson but for now let's push our code
to GitHub
foreign
there we go okay now we're going to add
a background camera movement and a tiny
bit of physics in our game so first
let's add a background image here's one
I made on piscal earlier you can see
that it's only 90 pixels wide by 32
pixels high so again we have to resize
our image so it's bigger otherwise if we
just scale it up in our game it will be
really blurry
so let's resize I'll just click resize
make sure these two boxes are checked
and I know my height of my game is a
thousand so when I resize it resizes the
content so now I'll just export it
download PNG
then I'll go over to my phaser demo
folder and let's add it in our assets
folder let's create another folder
called backgrounds and let's open up
another finder window with command n
downloads there's our background image
let's drag it into backgrounds
now let's load it into our game so it's
the same process as we did with Adam
we're just gonna
copy this line right here
except we'll give it another key
and we'll change the path of our image
so it's in the backgrounds folder and it
is called
tree BG or tree background so there it
is so now that it's loaded we can add
the image in our create function so
because in this example we won't be
manipulating the tree background in the
update function or with any event
listeners we can create a local variable
within our create function so we would
only have access to that variable in
this specific create function
so I'm just going to call it VAR tree BG
equals game dot add dot Sprite and again
Sprite is just another word for an image
and since images are drawn from the top
left corner we can just specify its X
position as zero y position zero and the
key of the image save our code refresh
our local server and there's our image
but obviously atom isn't on our screen
anymore and that is because images are
drawn on top of each other in the order
in which they were defined so these two
lines is where I'm drawing atom but
after these two lines we are drawing the
tree Sprite on top of atom so if we just
cut this line of code and paste it above
where we drew our atom image save our
code refresh we can see that atom is now
drawn on top of the background so I
think atom is slightly too big for this
background so we can change the scale of
our image with the following method
first you say the very table name that
represents the Sprite Which in our case
is atom so atom.scale dot set to
parentheses
and our first argument will be the width
scale
so if I say 0.7 the width of our image
will be will be 70 of its actual width
and let's do the same with height save
our code refresh and now atom is
slightly smaller so now we have a
background that we can move around on
let's just increase the speed by two
because I think he's moving a little
slow that's better okay so you'll notice
that our camera doesn't follow our image
we can go to the phaser documentation
and find an example that does what we're
looking for so here's an example of
camera movement and it uses something
called a dead zone so when you're in
this rectangle you do not move the
camera but as soon as you go outside of
the rectangle or on the edge you can see
that the camera will move with the
character and now we can just look at
the documentation and it looks like
these two lines are what makes the
camera follow the character so let's go
back and add those two lines so here we
can say gain Dot camera dot follow
parentheses and the variable that
represents our Sprite Which in our case
is atom we save our code refresh and our
camera doesn't follow our Sprite and
that is because we haven't set the
bounds of our game in other words the
camera in our game doesn't have a
reference point of where it should be so
to add the bounds of our game we can use
this line of code game Dot World dot set
bounds parentheses and then the X and Y
coordinates of where our bounds of our
game is and then the width and height
which in our case which in our case is
2813 because that's how wide our
background images and it's a thousand
pixels high so let's save our code
refresh now we can see that our camera
can follow our Sprite so now let's add
the dead zone so our camera only moves
when our atom image is on the edge of
this invisible rectangle that we want so
again we can just look at the
documentation and it's sort source code
they're using this line so we'll use the
same with the arguments changed out of
course so let's say game DOT camera Dot
Dead Zone equals new phaser dot
rectangle parentheses and for this
example we want our camera to be 600
pixels wide so about this wide
so our first argument will be the origin
of where our rectangle is drawn so let's
say Center X or the center of our game
World minus 300 because our dead zone is
600 pixels wide so when we subtract 300
from where our rectangle is being drawn
it's going to be drawn in the center of
our game we also want our rectangle to
be drawn from the top so let's just have
0 as the Y position which again is up
here on the top of the screen and now
the width of a rectangle and the height
of a rectangle
and it's a thousand because that's how
tall our game screen is so let's save
our code refresh and now you can see we
have a dead zone so there are a few
things missing and one of them is our
character should face the other side
when it goes left and there's an easy
way to solve this issue and we can do
that with scale we can actually just set
our x value for our scale as a negative
number so if I make this negative 0.7
save my code refresh you can see that
atoms facing the opposite direction so
now with that in mind we can just take
this line of code copy it and just paste
it
in our if statements so that when we are
pressing on the right arrow atom faces
the actual direction of his image and
when we press the left Arrow we will set
the scale X of our atom image to its
inverse value so let's save our code
refresh and now when I go right we're
facing right and when we go left he's
facing left so the last issue we're
going to cover in this video is the game
bounds so you can see that we have a
character that goes out of bounds and
that's not what we want we want to have
our character stay on the screen so to
fix that we have to add physics to our
game so whenever you're going to use
physics and phaser the first line of
code in your create function should be
initializing the specified physics
engine so we're going to be using arcade
physics so to initialize the arcade
physics engine we can just say game dot
physics dot start system parentheses and
our argument will just be phaser dot
physics dot arcade and arcade is in all
caps so now that we have our physics
initialized in our game we can add
physics to a specified image we can add
physics to a specified image so we can
just say gain Dot physics dot enable
parentheses and then the variable that
represents our Sprite Which is atom and
then below that to make our atom image
collide with the bounds of our game
world we can just say atom dot body dot
Clyde World bounds and set this value to
True save our code refresh and when we
go to the edge of our game we can see
that we are colliding with it same with
the bottom as well as the right side of
our game so the last thing we're going
to add is some kind of collision with
the road right here because you can see
that atom can actually jump really high
and just levitate in the air and that's
not what we want we just want Adam to be
able to walk on the road like in this
area so one way to fix this problem is
to just add an if statement in our
update function that just says if atom
is above this point keep them there so
let's see what the Y position of our
image is when atom is around this area
we can get that value with just atom dot
Y and our value and his y position right
now is 394. so now in our if statement
that checks if we're pressing on the up
Arrow key we can just add another if
statement inside and this one checks if
atom dot Y is less than 395 and if
Adam's y position is less than 395 like
it is here we will just we'll just set
atom's y position to 395. save our code
refresh and now when I go to the top of
the road we can see that he is stuck at
this point okay now we're going to add
animation to our atom image and then
we'll be done with State 0. here's an
animation that I created earlier so in
piscal they allow you to create frames
of an animation and if you'll notice
each frame is slightly different than
the frame before that and if you play
these frames very quickly you get the
effect of motion and if I wanted to make
my animation more smooth I would just
add more frames and the difference
between each frame would be even less
and so after you're done with your
animation you want to resize it and you
want to make sure that these two boxes
are checked and I'll just make my image
10 times bigger resize and then I'll
export it
and then over in our assets folder we'll
create another folder and call it Sprite
sheets open up another finder window
with command n go to downloads there's
our image I'm going to rename it atom
sheet because it's a Sprite sheet and we
already have another image called
atom.png so it's good to name your files
differently and let's just drag this PNG
into our Sprite sheets folder so if we
take a look at our Sprite sheet we can
see that it is each frame that we had
and piscal automatically glues each
frame to each other so that each frame
is the exact same width so let's go back
to brackets and instead of loading an
image for atom we'll load a Sprite sheet
and don't forget to change the path
and then you have to add a third and
fourth argument and that will be the
width and height of each frame in your
Sprite sheet so our image is 240 pixels
wide by 370 pixels high so let's just
put those numbers here 240 wide by 370
High save our code refresh and we can
see that our image looks exactly the
same that's because when you load a
Sprite sheet and you add that image to
the game it will first default to the
first frame in your Sprite sheet so how
do we add animation well there's this
example on phaser and it's exactly what
we want so when we look at the source
code it looks like they are creating an
animation where they State the name of
the animation so this animation is
called walk and then they are listing
the order of the frames in which the
animation is played and then to start
playing the animation they just use the
animations.play method so let's choose
similar code in our state 0. so here
let's create a animation called walk so
we start off with atom dot animation dot
add parentheses and then the key of our
animation which we'll call Walk and then
the order of our frames which will be 0
1 2 3 4. so now that we have an
animation called walk we can play it
when we move left or right so in in our
if statements that check if you press
the right or left Arrow key we'll just
say atom dot animations dot play
parentheses and then the key of our
animation which is walk and then our
second argument will be the frame rate
so that could be anything from 0 to 60.
so let's just say 14 and then our third
argument will be if our animation loops
and because we are walking we want to
Loop because it's a constant cycle of
moving your left leg and then your right
leg but if you're making an animation
for something like shooting a bow and
arrow once you would have this set to
false unless your character had a rapid
fire bow and arrow where you would keep
on looping the animation so let's just
copy this line of code and paste it in
our if statement that checks we press
the left Arrow key save our code refresh
and now we can see that we have
animation but you'll notice that our
animation keeps on going even when we're
not moving so to fix this we can just
call the stop method so if we're not
pressing on the right arrow key or the
left Arrow key we'll default to this
else statement and say atom dot
animations dot stop parentheses and then
the key of our animation and that stops
the animation from playing so if we save
our code refresh you can see that when
we stop walking our animation stops but
you'll notice it is stuck in the last
frame that was displayed while the walk
animation was still playing so to fix
this we can just set the frame of our
Sprite sheet to zero because the first
frame or index 0 is just standing so we
can just type atom dot frame equals zero
save our code refresh now when we stop
walking he always stops in the first
frame which is standing
and that's it you just finished state
zero now's a good time to push my code
to GitHub so we'll just open Terminal
CD and here's a trick that I haven't
taught yet instead of typing out the
path of where your directory is you can
just type out CD and then space and then
you can just drag your folder into the
terminal and it writes the path for you
enter
and you can see that I'm at phaser demo
let's go over to GitHub
and it looks like we successfully pushed
our code now we're going to start
working on state 1. the final result
will look something like this so This Is
state one we have a tile map and our
atom image that can move on the screen
he can collide with the rocks and the
dark patches of grass and you can see
that we are console.logging what we're
hitting when we collide with either the
rocks or the dark patches of grass
so before we start coding let me change
the theme of my text editor
so that it's dark it's just easier on
the eyes in my opinion and now I'm going
to make our code less redundant so if
you'll notice in each state we're saying
we're console.logging the state number
and that's really redundant so instead
of console.logging the number of the
state at the beginning of each state in
the create function let's just
console.log in our change State function
so I can just say console.log
and then State plus State num save my
code refresh okay so now we are getting
to console.log so we know it's working
and now let's just delete our
console.logs for our state numbers
foreign
refresh
and everything seems to be working now a
small issue here is that when we first
refresh our game it doesn't print out
state zero but that's okay if we don't
get state zero printed out at the
beginning it's nothing too important
okay now let's start working on state
one so to create a tile map you have to
download the tiled tile map editor so if
you just go to map editor.org just
download it for whatever operating
system you have and once you have that
installed you can start making tiles so
here's some tiles I made they're just
some kind of grass so the standard for
tile size in tile Maps is 32 pixels wide
by 32 pixels high but you could have any
size tile that you want just be sure
that it's a perfect square so this will
be its own tile and this will be its own
tile so let me just export this
and you'll see that we just got a Sprite
sheet but the tiled map editor will
split this image in half so you don't
have to worry about having a different
file for each tile the tiled map editor
will automatically break up the images
so here's another tile that I'm going to
put on my tile map except this one's 96
by 96 and that's important because 96 is
a multiple of 32 which will be the size
of our tiles and again we can just
export this put it in the tiled map
editor and tiled will automatically
break up our image into nine tiles
because 96 is 3 times 32 so I'll just
export this
and now let's go to our phaser demo
folder and go to our assets folder make
another folder and let's call it tile
Maps
and make another finder window with
command n go to downloads
and let's just drag our two images to
our titlemaps folder okay now let's open
up titled
and let's create a new tile map and when
you make a new map make sure that the
orientation is orthogonal so we have
square tiles the tile layer format is
CSV and not base64 encoded because
phaser doesn't support base64 encoded
tile maps and then you can just set the
height and width of your tile map to
whatever you'd like and our tiles are 32
pixels wide by 32 pixels high so this is
correct and let's just click OK and now
now we're going to add our tile set
images so let's say we don't have any of
these side toolbars here we can just
bring them back with View
and let's select tile sets because
that's what we're going to be that's
what we're going to be adding
now let's bring up our folder with our
tile set images
and just drag them in
so this tile set will be called Rock
tiles all this information is correct so
I'll just click OK and you can see that
it automatically breaks up our image
into nine tiles now let's add our grass
tiles
click ok now we have our gas tiles so
one thing to keep in mind is that you
can't add images to your tile set all
the tiles for a specific tile set have
to be on one image file so I can't make
another rock on pistol and then add it
to my rock tiles tile set I would have
to create another tile set up here so
let's just add some grass so I'll just
select this tile click the bucket or the
shortcut is f for fill and then I'll
just add the grass to my tile map zoom
out and I'll add some more grass except
I'll use the stamp brush and just add it
wherever
and I'll add some rocks
so I can just highlight this entire
image and then just put it wherever I
want to except you'll notice that our
grass tiles here are gone and that we
can see past the rock so what we have to
do here is add another layer so I'll
just undo what I just did with command Z
and then I'll bring up my layers sidebar
so now I can see I have one layer I'll
actually just name it grass and then
I'll add another layer and call it rocks
and so now that I have my rocks layer
highlighted whenever I add an image I'm
adding to the rock layer and I could
also deselect the grass layer to show me
whatever's on a specific layer
and I'll just add some more rocks
okay I think my tile map is finished now
so now we're gonna export it so before
we do that let's open up our map
property sidebar and it's really
important that the layer format is CSV
because again phaser doesn't support
base64 or XML
and now let's save our project with
command s let's just name this field
save it
so now we have it on our desktop and now
let's export it
export as and Export it as a Json file
and save now we can see that we have a
field.json file on our desktop okay now
that we've created our tile map and
we've exported it as a Json file let's
add it to our game so let's put our Json
file in our tile Maps folder
so now we can see that we have our Json
file in our tile Maps folder so now we
have to load our tile map with game dot
load dot tile map parentheses our first
argument will be the key for our tile
map then the path
and then null which isn't important for
right now but basically it's a Json
object that you could pass to it but
it's not important and the last argument
is phaser dot tilemap dot tiled
underscore Json and the reason why we
have to add this line right here is
because the default is a CSV file so we
have to let phaser know that we're going
to be using a Json file after that we
have to load our tile set images so we
can just say game dot load dot image
parentheses and then the name of our
tile set so grass tiles because if you
look at our tiled map editor we have a
grass tiles tile set and a rock tiles
tile set so we have to say grass tiles
and then the path for our towel satin
image let's do the same for our Rock
tiles tile set so that loads our tile
map and our tile set images so now let's
add it to our game so let's create a
variable called map and this will
represent our tile map now let's say
game dot add dot tile map and then the
key for our tile map now we have to add
our tile set images with map dot add
tile set images parentheses actually
there's no s and then we say the key of
our tile set image and we can do the
same for rocks and now we have to add
the layers to our tile map so let's
create a variable for each layer with
map dot create layer parentheses and
then the name of our layer which in our
case is grass and rocks so let's add the
grass layer first and do the same aim
for rocks see our code refresh your
local server and when we go to state one
there's our tile map so one thing that's
worth noting is that like Sprites our
layers are drawn in the order that they
were created so if we created the Rocks
layer first and then the grass layer we
don't see the Rocks anymore because
What's Happening Here is we drying the
Rocks but then we're using the grass
layer and drawing over the Rocks so keep
that in mind that the order of creating
your layers matters so just to review
first we have to load our tile map and
because we exported it as a Json file
you have to say that it's a Json file
otherwise phaser will default to a CSV
file and then we have to add our tile
set images and then we have to create a
tile map and then we have to say that we
are going to have a tile map then we
have to add the tile set images and then
we have to add the layers so that's how
you add your tile map to your phaser
project okay now let's add a character
to State 1 so that our character can
move around in our tile map and collide
with the Rocks so let's just use our
atom image
so here I'm just loading our atom.png
file now let's create a atom variable
and set it to that image let's put them
somewhere on our map there's our image
and if you're wondering why I don't have
to say VAR Adam it's because in state 0
we've already declared our atom variable
and so when we just switch to a
different file this variable atom
carries on to whatever file that you
switch to so let's make our atom image
smaller with atom.scale DOT set to
okay that's better now let's add physics
to our game with game dot physics dot
start system parentheses phaser physics
dot arcade and one thing to take note of
is that when you start physics in your
game that physics carries on to the
following states so this line right here
that I just wrote is redundant because
we we already started our physics in
state zero but if this were a separate
project then you would have to start the
physics like so now let's add physics to
our atom variable with game dot physics
dot enable parentheses then atom and now
let's add some input so that when we
press on the arrow keys atom moves so
instead of saying
game.input.keyboard dot is down Etc we
can use something called cursors so you
don't have to write all that stuff down
so let's create a global variable called
cursors and let's set cursors to game
dot input dot keyboard dot create cursor
Keys parentheses so this creates keys
for our up down left and right arrow
keys so in our update function we can
just say if cursors dot up or whatever
direction that you want dot is down and
then we could change the Y position of
our atom Sprite so let's save our code
and when I press the up Arrow key it
goes down and that's because I have this
switched around it's supposed to be
negative okay there we go but we want
our atom image to collide with the rocks
and part of that is instead of changing
the position of our Sprites this way we
have to use velocity so after we enable
physics on our atom variable we can use
velocity with atom dot body dot velocity
dot Y and then we could set the velocity
to whatever number so I'm going to
create a variable called Val or velocity
and then I'm going to set it to 500 save
our code refresh okay he's moving fast
enough so this should actually be
negative now let's add input for the
rest of our arrow keys
save our code refresh now we have our
character moving
in all directions and actually our
character doesn't stop so we have to add
an else statement where if our up and
down arrow keys are not pressed then our
y velocity should be zero
take that code and then set our y
velocity to zero and then we'll do the
same for X except change y for X save
refresh
go to State One
and
looks like everything's working fine
okay now let's add collision between
atom and The Rock tiles so first let's
say map dot set collision between and
then parentheses and this part's kind of
tricky because now we have to know what
the index of our colliding tiles are so
let's open our Json file and we can see
that here we have our rock layer and
anywhere that says zero that means
there's no tile put down but you can see
that we have the number is one two three
four five six seven eight nine so I get
the feeling that indexes one through
nine represent the rock tiles and if we
go up here where we can see the grass
layer we can see that there are tens and
11s so I get the feeling that the tens
represent this kind of grass tile and
the 11s represent the darker shade of
grass tile so with that in mind let's go
back to our state1.js file and The Rock
tiles ranged from indexes 1 to 9 and our
third argument will be true because it's
Boolean that says if collisions are
enabled or not and our fourth argument
will be the layer that will have the
Collision which is rocks and then in our
update function we have to check for
collision between our atom variable and
The Rock tiles so we can say game dot
physics dot arcade dot Collide
parentheses and then we're going to
collide atom with our rocks layer so we
actually have to have rocks a global
variable saver code refresh and now you
can see that we collide with our Rock
tiles and if you want you can add a
callback function for so that when we
hit our rock layer we console.log
something and this thing right here is
called an anonymous function it's
basically just the function without a
name so let's save our code refresh and
now whenever we hit rocks
we get hitting rocks in our console also
it's important to notice that at the
beginning of our state we're on top of
our rocks even though we should be
colliding with them it's only after we
leave the rocks or stop being on top of
them when we can actually collide with
the Rocks so that's just a kind of
physics Behavior to take note of
so previously phaser didn't support
multiple Collision layers but now you
can so let's say I wanted to collide
with the darker patches of grass I can
just set the Collision for one tile
index so I can just say map dot set
Collision parentheses and then I believe
the index for our darker patches of
grass was 11 and then I'll just set this
Collision for the grass layer and then
check for collisions for our grass layer
in our update function we also have to
make grass a global variable let's
change this to Grass save our code
refresh and now I can collide with the
rocks
and I could also collide with the darker
patches of grass at least and that
concludes State one so now let's push
our code to GitHub
there we go we just pushed our code to
GitHub so one thing to mention about
collisions and phaser physics is that if
you want your Sprite to collide with
something you have to use velocity
because if we just used what we did in
state 0 where we just said atom.y minus
equal some value save our code refresh
that is not the same as giving an object
velocity so if I go up
you can see that we don't Collide but
when I go in any other direction because
we're setting the velocity and we're not
changing the position like this we can
collide with things so that's just
something to keep in mind now we're
going to work on state two the end
result will look something like this so
here's state two all it is is a shooting
example where if you hold down on the
mouse you can automatically fire bullets
with no limits and you can also shoot
these Sprites and they will kill
themselves so one thing to point out is
that this Sprite right here is just a
regular Sprite we're using
game.ad.sprite but these three Sprites
right here these are part of a phaser
group so we are not making three
separate variables for each of these
Sprites which is useful if you have a
lot of enemies and that's pretty much it
so to start let's pre-load our images
and these are just images that I made on
piscal so now let's add the base to the
center of our screen
and now we have to set the anchor and
the scale of it
okay that's good now let's add the
barrel of the Canon
and again we have to set the anchor and
scale of our Sprite
okay all looks good now we're gonna make
the barrel rotate to wherever our Mouse
is pointing so in our update function
we're going to set the rotation of our
Barrel to gain dot physics dot arcade
dot angle
to pointer and our argument will be
Barrel
but because we are using Barrel outside
of the create function we have to make
Barrel a global variable so at the top
I'll just say VAR Barrel so that way you
can use the barrel variable anywhere in
our code save our code refresh
and there we go now we're going to make
our Canon fire bullets so let's make a
bullet variable and in our create
function we are going to make bullets a
group so we'll say bullets equals gain
dot add dot group parentheses and groups
are useful if you're going to have many
Sprites that are very similar to each
other in our case it's bullets now let's
enable a body on our bullets
set the physics of our bullets to Arcade
now let's add 50 bullets to our group so
let's say bullets dot create multiple
and our first argument is how many we
want to add so let's add 50 and then the
second argument is the Sprite Which is
bullet or the key of our Sprite Which is
bullet now let's make a fire function
and we'll call this function whenever we
click our Mouse and for now let's just
console.log
firing and in our update function let's
check if
game dot input dot activepointer dot is
down we are going to call our fire
method so let's save our code refresh
and whenever I click you can see that
our fire function is being called so now
let's add our bullets to our fire
function so we're going to make a
variable called bullet and we are going
to set Bullet to the first Dead bullet
in our bullets group
so we'll say bullets dot get first dead
and we are going to reset Bullet to the
location of our Canon which is at the
center of the screen so we'll say bullet
dot reset and we'll just say barrel.x
and Barrel dot Y and to make our bullet
move towards wherever we clicked our
Mouse we're going to say game dot
physics dot arcade dot move to pointer
and we're going to make bullet move and
our first argument is the Sprite that we
want to have move towards the pointer
and our second argument is the speed so
let's make a variable called velocity
and I'll just set velocity to a thousand
save our code refresh and now when I
click
you can see that we have
bullets but it's a burst of bullets and
then right after we fire more than 50
bullets we get an error and we'll fix
this error in a moment but first let's
fix the rotation of our bullet so we can
just say bullet dot rotation equals game
dot physics dot arcade dot angle to
pointer and then we'll get the angle of
the bullet to wherever our pointer is
save our code refresh oh I'm actually
forgetting a t
and there we go now our bullets are
facing in the correct orientation so now
let's fix this issue of having a limited
amount of bullets that we can fire so
one way to fix this is we can set every
member in the bullets group to kill
itself once it leaves the bounds of our
world so first we have to say bullets
dot set all and for every bullet in our
bullets group we are going to set the
check World bounds property and it has
to be in quotes and we're going to set
that to true and then we have to set the
out of bounds kill property to true so
let's save our code refresh and now
we can
fire more than 50 bullets so if I had so
what just happened right now was that we
have 50 bullets on the screen so in our
case when we have 50 bullets on the
screen there are no bullets that are
dead it's only after the bullets leave
the bounds of the world where the
bullets will kill itself so it'll be
dead and then get first Dead will get
the first Dead bullet in our bullets
group and it will reset that bullet to
the center of our Barrel so we can fix
this issue by one either adding a lot of
bullets to our bullets group so if I say
500
we won't run out of bullets and we won't
get our error that says we can't reset
our bullet the second option is to limit
the amount of bullets that you can fire
or limit the firing rate of your Cannon
so the way we can do this is we can have
an if statement that checks for the time
that you last fired a bullet and it will
check if that time is greater than the
desired firing rate so let's just make
an if statement and put all of this
inside the if statement
and we are going to make a global
variable called Next fire and we're
going to set that to zero and we're also
going to make a fire rate variable and
we're going to set that to 200 and then
in our if statement we are going to set
next fire to gain dot time dot now and
then we're going to add fire rate to it
and then between the parentheses we're
going to check if gain dot time dot now
is greater than next fire save our code
refresh
and now we have a limited firing rate
so what's happening here is
game.time.now is how long the game has
been running for so if I type it out
right now you can see that we've been
playing for about 22 seconds because
this number is in milliseconds so every
time we fire we are setting next fire to
the amount of time played plus fire rate
and what this number represents is the
time that you are allowed to fire
because if game.time.now is less than
next Fire or the time that you're
allowed to fire we won't fire a bullet
so now let's clean things up so we don't
need 500 bullets in our bullet group and
you'll also notice that our bullets are
being drawn on top of our Cannon barrel
and they're slightly offset so first
let's draw the bullets underneath the
cannon barrel and we can simply do that
by switching up the order in which we
draw the Sprites so first we're going to
draw the base of the Canon and then
we're going to draw the bullets and then
we're going to draw the barrel of the
can save our code refresh
and now our bullets are being drawn
underneath our Cannon barrel and now
we're going to set the anchor of our
bullets and the scale so that they
render properly and it looks like
they're coming out of the cannon Barrel
so to do that we can just say bullets
dot set all anchor dot Y and we're going
to set that to 0.5 save our code refresh
so that centers our bullet and we don't
have to set the anchor.x of our bullet
because all we care about is drawing the
bullet from the center of its height and
now let's set the scale of our bullet of
our bullets group so let's say bullets
dot set all and set scale X and we're
going to set it to 0.85 and let's do the
same for y and there we go now I don't
think you can set scale just by itself
to 0.5 so it looks like it doesn't work
so you can't use scale and settle you
have to state if it's dot X or dot y
okay now we're going to add enemies so
that we could shoot them with our
bullets so first let's make a enemy
variable and let's just set that
variable to a Sprite with game dot add
dot Sprite and we'll just use the atom
image from state 0. so there he is now
let's enable physics on our enemy with
game.physics DOT enable enemy and then
in our update function we want to check
if bullet is overlapping with enemy and
if so we will call a function so to do
that we can just say game dot physics
dot arcade dot overlap and the first two
arguments will be the two Sprites that
we want to have overlap so that will be
the bullets group and the enemy and the
third argument will be the Callback
function that will be called when these
two Sprites overlap so I'm going to make
a method called Hit enemy and for now we
will just console.log hit okay so now in
state two we can see that whenever a
child of the bullets group overlaps with
enemy it console.logs hit so now what we
have to do is we have to kill the enemy
Sprite and the bullet Sprite so to do
that we have to make bullet a global
variable so that way you can use the
bullet variable anywhere in the code and
then in our hit enemy function and then
in our hit enemy method we will just say
enemy.kill and then we will just kill
the bullet variable save our code
refresh
there we go so now let's add a group of
enemies to shoot because sometimes when
you have a lot of enemies in your game
it's better to use groups rather than
creating a variable for every enemy so
to start let's create a another Global
variable called enemy group and we will
set enemy group to a group with game dot
add dot group and then we'll say enemy
group dot enable body to true and that
will allow the enemy group to use
physics and then we'll set the enemy
group physics body type to phaser dot
physics dot arcade and arcade is
supposed to be in all caps so this is
just saying we're going to use the enemy
group is going to use arcade physics and
now let's just create a for Loop to
create the enemies so to create an enemy
we can just use enemy group dot create
the first two arguments will be the X
and Y will be the X and Y position of
that child in the group and then the
third argument will just be the image to
use for that child so let's save our
code refresh nope I forgot to write an i
it's supposed to be a lowercase h
okay so there we go
so the bullets and the enemy group
aren't colliding but that's because we
haven't coded that yet but for now let's
change the size of the enemies in the
enemy group so I'll just say enemy group
dot set all and what set all will do is
it will set the specified property for
each child in the enemy group to
whatever value you want so let's just
change the anchor for each child now
let's set the scale for each one okay so
that's better
and then in our update function we can
just use the same line but instead of
enemy we will say enemy group and then
we will make another method called Hit
group
and because this is a group that we are
checking for overlap we have to specify
what we want to kill so I'll just give
this method two arguments B and E for
bullet and enemy and let's just say B
dot kill and E doc save our code refresh
and looks like everything's working so
the reason why we got to say B dot kill
in the hit group method but we don't
have to make a bullet argument in our
hit enemy method is because the
arguments that are passed to the hit
group method will come in the order of
these arguments so if we switch these
around
we can just give this method one
argument which is e and then we can just
use the bullet variable instead of B so
if we save our code refresh
everything works fine so that concludes
state two now we're going to work on
state three the end result will look
something like this so This Is state
three all it is is these three buttons
and things to take note of are that they
tint
and untint when you press and let your
mouse up and things to take note of are
that they make sounds when you press and
unpress them so
that's what they sound like and the one
and two buttons can go to state one and
state two and that's pretty much it so
to start I've already pre-loaded three
Button images so now we can just add a
button to our screen with game dot add
dot button parentheses and then the
first two arguments will be the X and Y
position of our button and then the
third argument will be the key of our
image which is in our case button one
and then the fourth argument will be a
callback function which will be called
whenever you press the button so we can
just use an anonymous function for this
example and let's just call the change
State function that we made back in
state zero and the first argument should
be null and the second argument should
be the number of the state
so if we save our code refresh
and look at state three there's a button
and when we click on it we go to state
one so I'm going to make another button
and it's just going to be button two and
it switches to state two
there we go and I'll make a third button
that just does nothing for now at least
so we can just delete this callback
function so one thing we could add to
these buttons is to make them more
interactive so an example of that would
be for the button to change when you
press down on it and then go back to its
previous state when your mouse is up so
let's make a tint method and then we'll
just change the tint of the button that
calls it so we'll say this dot tint
equals 0x and then six B's and this is
basically just a hex color so the first
two characters after the x is how much
red is in the tint the third and fourth
are green and the last two are blue so
let's change the tint of button three
whenever you press down on it so to do
so we can just say B3 B3 dot on input
down DOT add and then we'll say this dot
tint which is the function we'll be
calling when input is down down and then
the second argument is the context which
is button three so let's save our code
refresh and then the tint of our button
changes so let's add this feature to the
other two buttons so that all the
buttons can tint and now let's make a
untint function so that when you so that
when your mouse is up the button removes
its tint so this color right here is
just pure white and this is slightly and
this is and this is like a gray so to
make our buttons untint we can just say
on input up instead of on input down and
then let's change tint to untint and now
our buttons can tint and untint now
let's add some sounds to our buttons so
that when you press down on them they
make one sound and then when you let
your mouse up they make another sound so
in my assets folder I created another
folder called sounds and inside of it is
just an MP3 and what it is is just a
series of sounds
foreign
so those are our two sounds that we're
going to use and we don't have to have
separate MP3 files for each sound in our
game we can just Stitch all of those
sounds into one file and then we could
break them up in phaser so it's kind of
like a Sprite sheet except for sounds so
in our preload function we can just load
a sound with game.load DOT audio
parentheses and then we can just give
the sound a key just like our images and
then the path for our sound now that we
have our sounds loaded we can split them
up into different segments so let's make
a variable called sound and we will set
sound in our create function to game dot
add dot audio parentheses and then the
key of our sound will be the argument so
now we can split up our sound file into
different segments we can do so with
sound dot add marker parentheses and
then the first argument will be the key
for our sound so we have a lower pitch
to pop and a higher pitched pop so one
key will be low and we'll make another
marker for high so add marker needs two
more arguments and those are the start
and end points of the sound segments so
so my sound file is only a second long
so I'll just say the start is zero
seconds and then the end is 0.5 or low
and then for high we'll just say it's
0.5 to 1 second and now to play the
sounds and now to play the sounds when
we click on our buttons we'll just say
sound dot play Dot Low and then our
argument will be the key for our marker
which is low for when we press down on
the button and then we'll play high when
our button is let up so let's save our
code refresh
and now when we press on a button it
makes a sound and when we let up
it makes another sound so you might have
noticed that there was a really long
delay between pressing down on the
button and the sound playing
and the same goes for letting the button
up and that's just because the the end
points for my sounds are not an exact
fit so actually for my sound file the
low pitched pop starts at
0.15 seconds approximately and it
probably ends at 0.3 but that doesn't
really matter because there are no
sounds immediately after the pop so the
end point doesn't really matter for my
sound file and then for the high-pitched
pop it actually starts at 1.1 and ends
at maybe 1.3 but I'll just say 1.5 to be
safe so I'll save my code refresh the
local server and now the sounds are a
little more responsive
so that's state three now we're going to
start State four the end result will
look something like this so This Is
state four all it is is a bunch of
examples of tweens here we can see that
we are changing the values of these
Sprite objects this one Loops forever
and this one's opacity changes instead
of its position like all the other ones
and this guy will only tween once you
call a function to make it start so
that's State four
so what this state will focus on are
tweens so essentially what a tween is is
a way to change a value from one point
to another point in a certain amount of
time using a certain pattern and that
pattern can be something like linear or
bouncing but I think it'll just make
more sense if I just code it and show
you so to create a tween what you would
do would be game dot add dot tween and
the tween method takes an object usually
it's a Sprite but it can be anything
that has a numerical value so let's say
I want to Tween this first atom image so
I'll say A1 and if I want to Tween it to
a certain position I would just say dot
two parentheses and the two method takes
an object and this object will be the
will hold the properties that you want
to Tween to so let's say I want to Tween
this guy to the Y position of 400 so
next our second argument will be the
time and takes to go to this position of
400 so I'll say 2 000 for two seconds
and then the third argument will be the
pattern of my tween or the ease of my
tween and the most basic one would be
linear and the fourth argument will be
true and what this basically means is
the tween will start automatically
because by default tweens do not auto
start so this would be false so I'll
just save my code refresh
and there we go so you'll notice that
the Sprite went from up here to down
here in two seconds at the same speed so
we can change the ease of our tween by
just changing the third argument so if I
wanted the tween to be a bouncing tween
I would just say bounce
and now he bounces so to get the full
list of tweens I couldn't find it in the
documentation but if you go to this URL
or just search up phaser tweens you
could probably find this page this this
is the source code of the tween manager
in phaser and these are basically just
all the tweens you can use so if I
wanted to use this one I could just use
that for my third argument
and now he has a different tween so to
better visualize what these tweens would
look like you can just Google for
easings or just go to easings.net and it
has the patterns of every tween so the
first one we had was linear which is
just a constant speed and the one we
have now is the ease out bounce but when
we just type out bounce you can see that
it's the same thing as bounce dot ease
out so just play around with the tweens
and see what ease you like so let's make
another tween except this time we'll
create a variable so this is just stuff
I had from earlier so we'll make a
variable I and it's not a very good name
but whatever we will set I to a tween so
I'll say game dot add dot tween item two
two x 100 and Y to zero so you can
actually change multiple values in a
tween by just creating an object with
multiple properties and we'll make this
tween last one second so 1000 and our
tween can be elastic ease out and that
should look like
this guy
so I'll just put it there and we're not
going to have a fourth argument because
this tween isn't going to auto start so
I'll just save my code refresh
and now to start this eye tween we can
just say I dot start with parentheses
and there we go now let's make another
tween for the third atom image except
instead of using two let's use from so
to and from are very similar the only
difference is two will tween your object
to that certain value that you specify
here from will tween your value from the
specified value to its actual value so
I'll just say from and we will tween it
from the Y position of 1000 and this
will take one and a half seconds and the
tween will use will be circular ease out
put it there and this will auto start so
there we go it tweened from the Y
position of 1000 which is down here to
100. our fourth tween will change the
Anchor Point of our fourth atom image so
if we tween the fourth image and change
its anchor value like so
you'll notice that we get an error and
that's because for properties like these
you would put them here in the tween
method and then change the x value like
so
so a fifth argument that we could add is
a delay so I could delay this tween by
one second
the sixth argument would be if the tween
would repeat so if I say true
you can see that it repeats twice or if
you wanted to repeat the tween three
times you would say two so it repeats
twice after the first initial tween
and then our and then a seventh and last
argument would be if you want it to
yo-yo so if a tween yoyos that just
means it reverses itself after it
finishes its tween so if we set this to
true and run our code you can see that
at yoyo is back
our fifth tween will change the alpha
value of our atom image because tweens
don't necessarily have to change the
position of a Sprite they can change any
numerical value in an object so we'll
change the alpha value or the opacity of
our image to zero over one second using
the bounce ease
and it will automatically start
so there it goes so two more tricks I'd
like to show you so if you want your
tween to Loop infinitely you can just
set the repeat argument to false and at
the end of between you can just say Loop
parentheses and pass true as an argument
so now you'll notice that this guy right
here will Loop forever
so the last trick I'd like to show you
would be let's say you don't know where
you're going to be tweening to or the
value that you're going to be tweeting
to is always different instead of
tweening to a number like this we can
just add to that value by putting plus
or minus and the value that you want to
add to the specified value so pay
attention to the first guy where we are
going to add 400 to its y position
so that concludes State four okay now
we're going to work on state five and
the end result will look something like
this so here's State five
all it is is a simple platformer where
we have
Adam and he can jump on top of these
platforms
you'll notice that he can bounce when he
hits the ground
and obviously there's
vertical gravity
but he also has acceleration so
it takes time for him to build up speed
when I press on the left and right arrow
keys
and that's pretty much it so first I'm
just gonna preload an image
and that image will be of the platform
that Adam will be jumping on next let's
add atom to our game
so there he is next let's enable physics
on atom so we can just say game dot
physics
dot enable
and atom will be our argument after we
add physics to atom we can give him
gravity with atom dot body dot gravity
equals 500 and we have to specify which
direction the gravity is is occurring in
so we'll give him vertical gravity so
we're going to use dot y because Y is up
and down
so now he can fall down next let's make
him collide with the bounds of the world
so now you can see that he collides with
the world and let's make Adam bounce a
little bit when he hits the ground so we
can just say Adam dot body dot bounce
dot y equals 0.3
so you can see that he bounces slightly
when he hits the ground
and now let's just add some keyboard
input so that we can move Adam around
the world so in the update function I'm
just going to make a few if statements
that check if
some arrow keys are being pressed down
so if we were pressing the left Arrow
key we are going to add acceleration to
atom with atom.body.acceleration
dot X and we'll make a variable called
Excel
and it has to be negative because Excel
is going to be
positive number and then when we're
pressing down on the right arrow key
we'll just give him positive
acceleration
so when I press on the left Arrow key he
goes left and when I press the right
arrow key he goes
right
and then if we're not pressing either
the left or the right arrow key we'll
just set his acceleration we'll just set
his horizontal acceleration to zero
so right now I'm not pressing on the
left Arrow key but you can see that atom
does not seem to slow down so to make
him slow down we have to add drag to his
body
so we'll just say Adam dot body dot drag
dot x equals 400.
so now he can slow down whenever I let
down on the arrow keys so now I'm just
going to make another if statement so
Adam can jump up
except this time we'll just use velocity
because when you give a Sprite velocity
the Sprite moves right away but if you
give the Sprite acceleration it's going
to take time for the Sprite to build up
speed so let's save our code refresh and
now he can jump infinitely and that's
okay for this example okay so now we're
going to add the platforms and we're
going to use this platform image that I
made on piscal so up here I'm going to
make a platform variable and I'm going
to set platform to a Sprite
with game.add DOT Sprite
and then I'm going to enable physics on
this platform so actually instead of
saying this line again for a platform we
can just make the argument an array so I
can just say atom and platform inside
one array and that will enable physics
on both atom and platform and then in
our update function we have to check for
collisions between atom and the platform
so we'll say game dot physics
dot arcade
dot collide
and we will have Adam and platform
collide
platform doesn't have any
okay so now when I jump on it they
Collide but because it's a platform we
don't really want the platform to move
so to fix this it's super simple all you
have to do is say the name of the Sprite
so platform dot body dot immovable
equals true so this will just make the
platform immovable so it doesn't move so
when I jump on it the platform doesn't
move now let's say we have a bunch of
platforms it's not very wise to have a
variable for every platform in the game
so we wouldn't have something like
Platform One platform two platform three
Etc
we can actually just make a group of
platforms
so I'll just make a variable at the top
and call it
platform group and then I will set
platform group to game.add.group
so now that phaser knows that platform
group is a group we can create platforms
with it
so we can say platform group dot create
and then the arguments are the X and Y
positions and then the Sprite that you
want to use for the platform
and I'll make two platforms
so there they are we haven't added any
code so that they Collide so let's do
that now so let's just add physics to
the platform Group by adding it to this
array right here and then we are going
to use set all
and make all of the Platforms in
platform group
immovable
so we're going to set all so we're going
to say set all body dot immovable and
we're going to set it to true and then
in our update function instead of saying
game.physics.arcade.collide with atom
and platform group as our two arguments
we can actually just make this second
argument an array and just add platform
group to that array so now atom will
collide with platform and platform group
so I'm going to save my code
refresh and it looks like he's colliding
with the platform groups
so this concludes okay so now we're
going to start State six the end result
will look something like this so here's
State six you can see that it's a
volcano and it erupts every half second
you will also notice that there's a two
second delay between starting the game
State and the volcano actually erupting
so for this example all we're using is
Time Event and a particle emitter so
that's State six I've already pre-loaded
my images so we have so we have these
two balls that we're going to use for
lava and this volcano so to start let's
just add our volcano to our game so I'm
gonna make a variable called Volcano
and set it to a Sprite
and then I'm going to set the Anchor
Point of our volcano so that it appears
at the bottom of our screen
there you go so that's pretty much it
for the volcano now we just have to add
the time events and the particles so
actually we can just chain these two
lines and I don't think and delete this
variable so it all looks the same okay
so now let's add the emitter to our game
okay so now let's add particles to our
game so I'm going to make a variable
called emitter and we're going to set
that to game dot add dot emitter
parentheses so an emitter is basically
just like a point for particles to
appear so our arguments will just be the
location of our emitter so X and Y and
then our third argument will be the
maximum number of particles so we'll
just give this guy 2 000 particles next
we're going to make our emitter emit
particles and I misspelt it right here
so I'll fix that so to make our emitter
emit particles we'll say emitter dot
make particles and then our first
argument will be the particle that we
want to use so if we wanted to just use
one particle we would say something like
red ball so this emitter would only emit
red ball particles but we want to emit
the red and orange ball particles so
we're going to put this in an array and
it will be an array of the keys of the
images that we want to use so we'll use
red ball and orange ball the next
argument is the frame that we want to
use so if you had something like a
Sprite sheet you could pick what frame
you want to use but because we have an
array here it's going to be picked by
random so we can just make it zero so we
can just say zero because because that's
the default value and the particles are
going to be picked at random so it
doesn't really matter the next argument
will be the number of particles to
generate so we can just say 5000 and
then the next arguments are if you want
the particles to collide with other
arcade bodies so we don't have any
arcade bodies for this example so we'll
just say false and then the last
argument will be if the particles can
collide with the world so we'll make
that true
okay so now we can just start our
emitter and we can do so with just
emitter Dot start
parentheses and then our arguments will
be if the particles explode at once so
we don't want that so we'll say false
because we want the particles to come
out like a stream the next argument will
be how long the particles will last for
so each particle will last five seconds
so 5000 milliseconds and then the third
argument will be how frequent we want to
emit a single particle so we're going to
emit a particle every 20 milliseconds
saber code refresh
and now our emitter is emitting
particles so let's make our particles
jump up in the air more so that they can
Arc and it just looks like the volcano
is having a more violent eruption so we
can set the speed of the particles with
emitter dot Max particle speed dot set
parentheses and then we can just set the
maximum horizontal and vertical speeds
of the particles so for this example the
horizontal speed of the particles
doesn't really matter so I'll just set
it to 300 but we do want the particles
of our emitter to always go up so I'll
set the maximum speed to negative 300 so
it will have a velocity of negative 300
when the particle is first emitted and
then we'll set the minimum speed to
negative 100 so now the Y velocity of
our particles will always be between
negative 100 and negative 300 so it's
always going to go up and then we'll
just set the minimum x value to negative
300
so that looks a little better we can
also add gravity to the particles
with emitter dot gravity and we can just
set that to 300 so that the particles
will fall down faster
so now that we have our emitter working
we can add the time event so we can
change the way our volcano erupts so for
our first time event we'll give the
volcano a two second delay between first
starting the game State and the volcano
actually erupting so we'll say game Dot
time.events.add and then we'll say 2000
for 2000 milliseconds and then the
second argument will be a callback
function so we'll just give it an
anonymous function and let's take this
line right here and paste it inside the
Callback function so if we save our code
refresh we go to state six
you can see that it takes two seconds
for the volcano to start erupting so
this event is only added once so after
two seconds it calls this function right
here and it never calls this function
ever again so let's add an infinitely
looping time event with game dot time
dot
events.loop parentheses and our first
argument will be how often we want to
Loop this time event so we'll say every
half second or every 500 milliseconds
and then we'll give it a callback
function and in our callback function
we're just going to check if our emitter
is on and if it is on we're going to
turn it off and if it's off we're going
to turn it back on so we can just do
that with a simple if and else statement
so to check if the emitter is on we can
just say emitter dot on and if emitter
dot on is true we'll set it to false
else we'll set emitter dot on to True
let's save our code refresh
and there goes our volcano so this
concludes State six okay so now we're
going to work on state seven the final
result will look something like this
so here's State seven all it is is a
arrow that will point in the direction
that you swipe and and one thing to take
note of is that if you just click a
swipe doesn't register you have to swipe
a certain distance for it to register as
a swipe and if we change this variable
called leeway our code will have a
higher Tolerance on what will be
considered a swipe so that's State seven
so it looks kind of simple because it
kind of is but this game state is more
focused on algorithms which are
important when you're making games so to
start let's just add the arrow to our
game so here I've already pre-loaded our
Aero image so I'll make a variable
called Arrow at the top
and we're going to set Arrow to a Sprite
and we're going to put it in the center
of our game so there we go and now what
we want to do is we want to add event
listeners so that whenever our Mouse is
down or let up we want to call a certain
function so the way we can do this is we
can just say game dot input dot on down
DOT add and we'll have a function called
start swipe so here we can just say
start swipe is a function and for now we
can just console.log where our Mouse is
or where or where our finger is pressing
down if we're on a touch screen so to
get the position of the pointer you can
just say game dot input dot X and gain
dot input.y so I'll save the code
refresh have a extra T there now you can
see that whenever I click we get the
position of our pointer which in this
case is our Mouse but it will also work
if you're using your phone and you just
tap the screen with your finger so now
let's make a function that gets the
swipe Direction whenever our input is up
so we'll say game.input dot on up dot
add and we're going to make a function
called get swipe Direction and we can
just console.log the end points here by
copying the start swipe method so now
whenever I press down on the screen we
get the location of our pointer and
whenever I let up we get the location
again okay so now we're going to make a
few variables and we're going to call
them start point x start point Y end
point x and end point Y and then in our
start swipe and get swipe Direction
methods we will just set these variables
to the X and Y position of game.input so
now that our code knows where we're
pressing down with our Mouse and where
we're letting up with our Mouse we can
add if statement in our get swipe
Direction method to determine what
direction we just swiped in so the way I
approach this was if the change in X is
greater than the change in y then we
know for sure that the swipe was
horizontal else if the change in y
between the start and end points was
greater than the change in X then we
know for sure that it was a vertical
swipe so let's just code that now so
I'll make an if statement and an else
statement and in our if statement we'll
just console.log if it was horizontal or
vertical so here we're going to
console.log horizontal if the swipe was
horizontal and else we're just gonna
console.log vertical so now between the
parentheses I'm just going to check if
the change in y is less than the change
in X because if the change in X is
greater than the change in y then we
know it's 4 horizontal so we're going to
use the ABS method or absolute value so
that way it doesn't matter if the number
is negative or positive because if you
swipe from left to right then the change
in X is going to be a positive number
but if you swipe from right to left the
number is going to be negative but the
distance of the swipe was still the same
so that's why we're going to use the
absolute value method so I'll just say
end point Y minus end point start Point
y less than the difference between the x
value of our start point and our
endpoint okay so I'm going to save the
code refresh so when I swipe
horizontally we get horizontal and
actually we can just delete these
console.logs now so when I swipe
horizontally we get horizontal and if I
swipe vertically we get vertical okay so
now we're going to make our arrow point
in the direction that we swipe to so I'm
going to make a variable called swipe
Direction and that's going to be the
angle that our Arrow points at so right
now the angle is zero but if it's
pointing to the right it'd be 90 if it's
pointing down it'd be 180 and if it's
pointing to the left that would be 270.
so the last line of our get swipe
Direction method will be Arrow dot angle
equals swipe Direction so now let's set
swipe direction to to whatever direction
that we swiped in so for horizontal
let's make an if and an else statement
so if we're swiping horizontally and our
start point is less than our end point
then we know that we swiped right so if
my swipe starts here and ends here the x
value of my start point will be less
than the x value of the end points so in
code we can just say if end point x is
greater than start point x then swipe
Direction equals 90. so this is pointing
right and if this isn't true and we know
that our swipe is horizontal then the
only other direction would be la left so
that would be 270 so I'll save my code
refresh and now you can see that we can
have the arrow point in the left or the
right direction so now I'm just going to
take this if and else statement and put
it in vertical and then I'll switch out
the X for y's and then I'll switch out
the X's for y's so if our endpoint was
here and then our endpoint was here then
that would be down so we can just set
this to 180 and if it's not down then
it's up so then our angle would just be
zero so I'll save my code refresh
and now
we can swipe in all four directions so
one issue here is that if I just click
the arrow is going to point up that's
because when I click the starting points
and the ending points are the same so if
we start at this if statement because
our start and end points are the same
one is not less than or greater than the
other so it defaults to the else
statement and again here the start
points are the same so one isn't greater
than the other and so it just defaults
to up so one way to fix this is to just
have our get swipe Direction return
false if we are just clicking on the
screen so if the change in X or the
change in y is not greater than a
certain threshold then we won't do
anything so near the beginning of our
function above our if an else statement
we'll just say if and then we're just
going to return false so now I'm just
going to take the absolute value of the
change in y and say if it is less than a
certain threshold so let's say 10 so if
it's less than 10 and the change engine
X is also less than 10 then we're just
going to do nothing and return false so
here I'm clicking and nothing's
happening let's actually change 10 to a
variable called leeway
and now everything is working fine so
again this state wasn't necessarily
focused on phaser but more of but more
about algorithms and I thought that this
example would be really helpful if you
were going to make a mobile specific
game that incorporated swiping okay now
we're going to work on state 8. the
final result will look something like
this
so this is State eight it's just the
state that spells out text for you in a
specified width so it's very useful for
speech boxes or if you're just telling a
story in your game but it's also just
pretty cool to look at so adding text to
your game is actually pretty simple so
this this state focuses more on
algorithms which are which are important
so this is State eight
so adding text to your game is pretty
straightforward all you have to do is
say game dot add dot text parentheses
and then the arguments will be the X and
Y position of your text and then the
third argument is what you want the text
to say so pretty straightforward so now
we're going to make it more complex by
having the text type itself out which
will be really useful for speech bubbles
or telling a story in your game or just
making your game look more Dynamic so
here I have some lorem ipsum text which
is just Latin filler text it doesn't
mean anything and it's just text to fill
up space which will later be replaced
with actual sentences so let's make a
method called spell out text so we don't
actually need our update function for
this so I'll just replace update with
spell out text and what our method will
take will be the X and Y position of our
text the width of our text so how wide
the text box is the actual text that we
want to display the font size the speed
at which the text is spelled out and we
can have an optional font so when we
call Our Spell out text method it's
going to first display one character and
then it's going to display the next
character and then the next character
and then the next character Etc so it's
going to be a loop so let's make a
variable called Loop and let's set it to
game dot
time.events.loop parentheses and the
first argument will be the speed so how
often this Loop event is going to Loop
and then the second argument will be the
function that we're going to call and we
are going to make a function called add
Char so here I'll just say function Char
and the add Char function will append
one character to the text that it's
supposed to be displaying so up here
let's make a variable called sentence
and we're going to set it to some kind
of text so our first argument will be
the X and Y position which we'll get
from these two arguments here initially
sentence will have no text in it so we
can just make an empty string and
because of this Loop event it will
append a character to this empty string
every however many seconds it will
append a character to this empty string
every time this event Loops so after
this empty string we'll make another
argument and that argument will be an
object and this object carries anything
related to the font of your text so for
example I can change the font size of
the text with font size
and here we have a pretty big font I can
also change the color of the text with
fill so if I wanted it to be white I
could put in the hex code for a specific
color and there are a few more options
but we're just going to use font size
fill and the actual font of the text in
this example so going back to this
argument inside this object we are going
to set font size to font size plus PX
which is or which is short for pixels
we're gonna make fill the fill color so
I guess we should add fill here and then
we're going to add the font so this font
will correspond to this font this fill
will correspond to this fill Etc so now
we have to write some code that appends
each character to our sentence variable
so let's make a variable called index
and the index will be the index of where
we are in terms of how much of the
sentence we've typed out so initially
index will be zero because the first
character that you want to print out is
index 0. so in add Char we can just say
sentence dot text plus equals text
brackets index and then we are going to
increment index by one every time we
call the add Char function so now let's
call the spell out text method so we'll
say this dot spell out text and now
we'll just put in some arguments we
haven't done anything with with yet so
any number will do and we will use this
alarm ipsum text and we're going to add
a character every and our font size will
be 30 and we're going to add a character
to this text every 40 milliseconds and
fill can just be white
and we haven't added anything for font
so the font will just default to phasers
default font so let's save the code
refresh
and there it is now it's typing itself
out except it goes off the screen and
also when our text is finished typing
itself out you can see that we get this
error because right here once the index
is greater than the length of the text
string it's out of bounds and so we have
to stop this loop from looping once
we're at the last index so let's first
fix the issue with the text going off
the screen my solution to this was to
make an invisible text that you couldn't
see and once it was a certain width we
would know to add another line to this
text that we can see so I'm going to
make a variable called current line and
let's just put it at the top of our game
and because we want our text to be
invisible we don't need fill and now we
can add logic to see when we can add
another line to our sentence so you'll
notice that if sentence was a global
variable text and phaser have a width in
pixels so while we're adding characters
to our sentence we can check the width
of our invisible line at the top and if
it's greater than the specified width
then we'll just make the text from
sentence go to another line so current
line will have the same text as sentence
the only difference is is once it
reaches the specified width then we will
delete the text that it currently has
but it will still keep typing out the
next text that is being added to
sentence so let's make an if statement
and in it we are going to check if the
width of current line is greater than
width so this width up here that is so
this width right here so if the width of
current line is greater than width we
are going to make sentence go to another
line I mean and we can do so with a
backslash n so backslash n will just
mean go to another line in JavaScript
and we are going to set the text of
current line to an empty string so let's
save our code refresh
and now our text is working except you
can see that once we ran out of text the
character that's supposed to be added to
sentence and current line is undefined
but you'll also notice another issue is
that we'll go down to another line
regardless if it's in the middle of a
word or not so let's just add some more
logic here that checks if the current
character is a space so we'll say text
bracket index equals a space so that way
only if the current character that's
being appended to sentence is a space
then we'll go down to a line otherwise
it will finish that word until it
reaches a space and then I'll go down to
another line so let's run our code
forgot another equal sign and sorry for
not making this English but but the
words are being printed out in full so
sentence is not going down to the next
line when it's in the middle of a word
so now let's fix this issue of printing
out an undefined character and again
that's because once index is greater
than the length of our text string this
character at text bracket index does not
exist so that's why it's printing out
undefined so now let's make another if
statement that checks if we are on the
last index of our text string so if
index is greater than or equal to text
Dot length minus one then we're going to
stop this game loop I mean and we can do
so with game dot time Dot events.remove
and we can remove the variable that
corresponds to the game Loop and let's
also console.log stop so let's save our
code refresh
and it looks like it worked pretty well
so now let's make the text of current
line invisible because we don't need to
see it anymore and we can simply do that
with currentline DOT Alpha and Alpha is
just the opacity of something so let's
just set it to zero which means you can
see right through it
so there we go okay so now let's add
some different fonts because phaser has
this one default font and you don't want
your font to look like everyone else's
font and you don't want your game to
have the same font as everyone else's
game so we're going to use Google fonts
so if you head over to Google fonts
there's an array of different fonts so
I'm just going to pick two of them and
once you've found your fonts you want to
click this button and then you want to
scroll down and hit the JavaScript tag
and you want to copy this line right
here so you don't want to include the
https colon next in your preload
function we have to load that script so
we'll just say game dot load dot script
and then our first argument will be web
font in quotes and then the second
argument will be what we just copied in
quotes and one and once you have this
line written down you only need to
include this line once even if you have
multiple fonts
so go back to Google fonts and you also
want to copy this object web web font
config so just copy it and paste it
there and what this object is for is so
that this script knows what fonts to
load so now if we want to use this font
we can just take this word right here
and we don't need to include these two
colons in fact we don't even need these
so we can just delete them and let's
give this text some font and let's
change the font of this text to the
Google font that we just loaded and
let's make the font size a little bigger
so now you can see that we have a
different font so now let's get another
font this one looks cool and we could
just take the font go to the JavaScript
tag and we can just copy this part and
add it to the families array and let's
call spell out text again except we'll
change the font and let's change the
color and let's change the speed
so actually that's pretty hard to read
so let's just make it black
so there we go that's State eight okay
now we're gonna work on state nine and
the final result will look something
like this okay here's State nine it is a
high score system that uses Firebase and
Firebase is basically just a database
that updates in real time there are two
buttons button one generates a score
between zero and a hundred and it takes
the array from our database
sorts it and then pushes it back to the
database and button 2 just clears the
database so if we open up another window
and go to the same URL you can see that
when I change the score here
it also changes in the other window and
just to prove that this that these high
scores are connecting to the same
database and that the input that I'm
putting in my computer is not going to
both windows I'll go to state 0 and you
can see that only one window is affected
at a time so this high score system is
actually being connected to a database
so that's State nine so first let's make
some test data so that we get the text
to work in our game and then we'll
connect to Firebase later so up here I'm
going to make two variables HS text
which will be the text representing the
high scores and we'll set it to an array
and you'll see why later and then the
second variable will be
HS or just high scores and we'll make
this an array that goes from 10 to 1.
and now in our create function let's
make a for Loop and our for Loop will
Loop 10 times and here we're just going
to add text that shows the ranking of
each score so our so we can just say
game dot add dot text parentheses then
we'll put the X position and then the Y
position so the first number which is
one will be put at the Y position of 100
which is around here and then every time
we Loop we want to increase the Y
position so we will just add I times 90.
so each Loop will put the text 90 pixels
lower than the previous text and the
text that we will display is I plus a
DOT and let's give this text a font size
of 40 pixels save our code refresh okay
it looks like we're cutting off the 10
so let's just change this 100 to 20 okay
so you'll notice that all the numbers
are in line until we reach the number 10
and that's just because 10 has one extra
character so we can change the Anchor
Point of the text so that they are drawn
from the right side to the left so we
can just say anchor dot set to
so we'll put one so it will be drawn
from the very right side of the text and
we don't really care about the Y so
we'll just put zero okay so now all the
numbers are in line now let's make
another for Loop and what this for Loop
will do is it will iterate through every
element in the high score array so our I
equals zero is less than ten and then
we'll increment I by one after every
Loop so every time we Loop we are going
to add an object to this to the high
score text array and that object
represents a line of text and phaser so
I'll just take this line right here and
paste it and then for the text we will
just have the HS array and then we'll
get the element from that array so we'll
just put in I and it looks like it's
offset because we are not incrementing I
because I in this for Loop is one less
than the I in this for Loop so we'll
just say I plus 1 and put them in
parentheses okay now we have our high
scores displayed properly okay so now
let's connect to Firebase so what you
want to do is you want to go to
firebase.com and log in and then once
you're at the dashboard you want to
create an app so I'll just name this
phaser demo and then click create new
app and then click manage app so this is
our database okay so now we have to
download Firebase and put it in our app
so I already have everything installed
on my computer but to start using
Firebase what you need is to install
node.js so just go to nodejs.org and
download it and after you've done that
you want to go to bauer.io and when you
install node.js they also install npm
which stands for node package manager
and we're going to use Bower to install
Firebase so what you want to do is copy
this Command right here and then open up
your terminal and then you want to paste
the command here and press enter if it
gives you an error what you have to do
is say sudo npm install G Bauer and then
it will prompt you for your password and
then it should download properly but you
need to have node installed to use npm
so just write this command down and
press enter I'm not going to do it
because I already have it installed next
what you want to do is you want to use
this Command right here so so you can
just type it out or go to this URL on
GitHub and then in terminal you want to
change directories to your project so
I'll just say CD space and then I'll
drag in my folder to get the path enter
and then you want to paste the command
here
and press enter and now we have a bower
components folder in our directory with
Firebase in it now what we have to do is
load Firebase as a script in our
index.html file so at the top right
below phaser.min.js we'll create another
script tag and we will set the source to
Bower components Firebase and then
firebase.js and close the tag now over
in state 9 we want to create a variable
called ref which is short for reference
and then in our create function let's
set ref to new Firebase parentheses and
then you want to take this URL right
here which will be different because
everyone will have a different name for
their app and then you want to paste it
between the parentheses just like that
so I'll save the code go to state nine
and then open up your console and if I
type in ref you can see that there's
some code it's kind of hard to
understand but it's just a reference to
your database so now what you want to do
is create a variable called object and
we want to set it to an object with a
property of HS or high scores and it
will just contain 10 zeros in an array
so now we can just send this array over
to Firebase so what you want to say is
ref dot set parentheses and our object
will be the argument so I'll press enter
and now if you go over to Firebase you
can see that we have now saved our high
score object with our 10 zeros next
we're going to get the data from
Firebase and we're going to replace this
text with the actual data so in the
create function let's say ref.on and
then our first argument will be value so
whenever we get a new value we are going
to call this callback function which
will be our second argument and then our
callback function will take one argument
and we'll just call that snapshot which
will be all the data that's in our
database so whenever we get a new value
and we call this callback function our
callback function should re-render the
text so we have to make a function
called update high score text and what
we're going to pass it is Snapshot and
then to get the actual value of what's
in snapshot we had to call the Val
method and Val will be this entire
object so we have to say dot HS to
access the high score property so I'm
just going to comment this line out
first and then I'll just console.log
what snapshot is to get a better
understanding of how Firebase works so
I'm going to save the code and refresh
the local server and when I go to state
nine oh I spelled console wrong okay so
this right here is what snapshot is so a
lot of this information is just stuff we
don't need so we have to say snapshot
dot val and then the parentheses so now
this is what's being console.logged and
you can see that it's an object with our
high score array and so we just have to
say dot HS at the end to get the array
of high scores and if I go over to
Firebase I can manually change the data
so if I wanted the first one to be 82 I
could just type it in press enter
notice that we have a new value in our
database and then we'll just call this
callback function again so I'll delete
this console.log and uncomment this line
and now we're going to make our update
high score method and this method will
take an array of high scores and what
we're going to do is just change the
text of HS text so I'm going to take
this for Loop
copy it and just paste it here and then
we can just say HS text bracket I dot
text equals an element in the high score
array so now if we try to call this
update high score text method with this
dot update high score text
you can see that update HS text is not a
function so if we console.log this
inside this callback function you can
see that this is the window of our
browser so one way to fix this is to
just create a variable outside of this
callback function and we'll just call it
update HS text and we will set it to
this dot update HS text and we'll delete
this here so I'll save my code refresh
and there we go now we're connected to
Firebase now you can just change the
data here and it re-renders the text
now let's add some buttons so that we
can simulate sending a score to Firebase
and re-rendering the text and we'll have
a second button that just clears all the
high scores so in our preload method
let's load some Button images that I
made earlier and now let's just add
those buttons to our game with game dot
add dot button so there's our two
buttons and now let's add some
functionality to them so button two is
just going to clear our database of all
the high scores which is pretty easy all
you have to do is say ref.set
parentheses and then we'll just set an
object with an HS property and an array
of 10 zeros so let's save the code
refresh so right now our database has 82
and 3 but if I press button two you can
see that our text went back to zero and
now our high score array is all zeros so
pretty simple now what button one will
do is it will simulate sending a score
to Firebase so let's make a variable
called score and we're going to set it
to math.round and between the
parentheses we'll say math dot random
parentheses times 100 and then let's
just console.log our score so let's save
the code refresh and now whenever I
press 1 you can see that we get a random
score every time I click on it so now we
have to get the object that we get from
Firebase so I'm just going to make a
variable up here called FB object or
Firebase object and we are going to set
FB object to
snapshot.val.hs and because Firebase
object is a global variable we can use
the same reference here in this callback
function and here in this callback
function so after we create a random
score let's take FB object
so FB object is kind of a bad name for
our high score array so and you might
want to add other stuff to your to this
object so I'll just delete dot HS right
here and I'll just put it here and then
in this callback function we will take
FB object.hs and we will push our score
to it and then we'll send FB object back
to Firebase with ref dot set parentheses
FB object
save our code refresh so now when I
click one a random score is 54 and now
you can see that we have an array with
54 added to the end so now we have to
sort our array and we have to cut it to
the length of 10 because we're only
going to have 10 high scores so right
after we push score to the high score
array in FB object we have to set FB
object.hs to FB
object.hs.sort and then sort will take a
callback function that takes two
arguments A and B and it will return B
minus a and this will sort the array
from largest number to smallest number
so for example if I had an array of
random numbers and digested sort without
a callback function you can see that it
sorts in a way that's kind of like
alphabetically so you can see that it
sorts by the first number so two three
four four five so by adding this
callback function we're having it sort
from greatest number to lowest number so
actually we can just take this sort
right here and put it here so now it
sorts from highest to lowest and if we
switch B minus a with a minus B you can
see it sorts from lowest to highest so
this part sorts the high score array now
we just have to cut it so that it's
always the length of 10. and we can do
so with slice and it will start at zero
so it will include index 0 and it will
stop at index 10 but it won't include
index 10. so this will slice the array
from 0 to 10 including index 0 but not
including index 10. it stops at 9. so
let's save our code refresh and now
whenever I click the one button you can
see that we are adding a score to our
Firebase high score array and it also
sorts the scores so here we're creating
scores that are lower than the last high
score and so you can see that they're
not being appended to the high score
array and if we click two it resets the
high score and then you'll also notice
that when we first go to our state for a
split second you can see our original
high scores so we actually don't need
this high score array and we can just
replace that text with an empty string
and I'll just delete it
so there we go now we're going to add
some security to our database because
anyone with Firebase installed on their
project can just use this line right
here and read and write data to Firebase
so the simplest way to secure your
database is to use a custom token so if
you go over to your dashboard for your
app we want to set security rules and
we'll just set re the read and write
properties to off or authorized not
equal to null and this just says people
can only read and write data to this
database if auth exists so I'll save
those rules and now when I restart State
9 you can see that nothing happens
because we're not authorized to read
data from the database so now we have to
so now we have to authorize ourselves so
that we can read and write data so if we
go back to the dashboard and click
Secrets you'll you'll see this key and
what you want to do is copy this key
which you should never share with anyone
except people working on the project and
then to get authorized we'll say ref dot
off with custom token parentheses and
our first argument will be that key so
in quotes just paste it there and then
our second argument will be a callback
function and all this function is going
to do is say if you were authorized or
not so it will take one argument which
is just here and if error exists then
we'll console.log error else if there is
no error then we'll just console.log
authorized so now with the correct code
we can see that we were authorized and
now we have access to the database
however if I our code is incorrect so
I'll just add a zero at the end so it's
not the correct custom token
you can see that we get an error and we
can't read or write from our database so
I'll change this back to the correct
custom token and that's it and because
Firebase is real-time data you can see
that the code from Firebase changes in
real time whenever I click the button
that adds a new score
as well as deleting the scores
and I can change the score here
and it will also change in real time so
that concludes state 9.
hello it's come to my attention that the
Firebase portion of this tutorial is out
of date so in this video I'm going to
teach you how to update the state 9 of
this phaser demo so that it uses the
latest version of Firebase which looks
like this now
so the first thing you want to do is you
want to delete Bauer components
um you don't you no longer need Bower or
node next thing you want to do is in
index.html you want to delete that line
that Imports the uh
the Firebase component from the Bauer
components folder
in state 9 you can
delete this URL
as well as
make Firebase lowercase
and then to get the database you just
say dot database
call that method and then you have to
say ref for like where in the database
you want to
store this data which for now it will
just be at the root of the database so
you just use a forward slash
so
after you've done that you can delete
this block of code which authenticates
the Firebase stuff
for you
and
if we save our code
it's not going to work because there's a
lot of stuff that needs to be done
on the console so once you log into the
Firebase console you want to create a
new project
I'll just call this state nine
create project
and
set up
the debugger console stuff here while
that's loading okay so we're getting
this error Firebase is not defined
makes sense okay so this is the console
first thing you want to do is in
database
once you click the database tab go to
rules and this
these uh two lines right here basically
just say if the if the client side code
has not authorized uh their Firebase
database it means they can't read or
write so if authentication does not
exist then you cannot read or write so
this tutorial doesn't Focus purely on
Firebase it's this is just an example of
how you can use Firebase in phaser so
I'm going to
ignore this whole authentication part
and just say true and this is dangerous
because this means that anyone who
connects to your database can read and
write and that's not good but again this
isn't really a tutorial on Firebase and
and this is just for the sake of showing
you how you can use Firebase in phaser
so now that we have set these
to true you can publish them
next in
overview
you can select what platform you want to
use Firebase in so we're using the web
so click that web button next you want
to copy this block of code and paste it
right here
so if we save this
and run our code
and it says it cannot read the HS
property of null and that's because in
our database
there is no HS property it is null
so
we have to add a property in our
database called HS and one way to do
that is to just do it in our console
so if we enter console we can type in
ref and we can see that it is connected
to Firebase because it returns this
object
so to create the HS property just do ref
dot set and that's a method that takes
an object
and in this object we'll have the HS
property and it's a high scores
it's a high score list so we'll use
an array and we'll just pass in 10 zeros
so
that's 10 zeros I think and just press
enter
okay so you can see that we now have
zeros here
and in our database we have the HS
property
and we have 10 zeros
so I think that's all we need to do so
if we just refresh everything
go to state nine you can see that
it is now populating our database with
simulated scores so hopefully that was
helpful and please leave your comments
on these videos if you have any
questions
or would like to give me any feedback
thanks