Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

16. September 2014

 

It is getting more and more common for kids of younger and younger ages to show interest in game development.  In this day and age there is a wealth of information out there, possibly too much information at times.  This guide is intended to help parents or younger readers get started in the world of game development.  So, what exactly does this mean?  First it means I will focus on technologies that are appropriate to beginners.  Second, it means I am making no assumptions about your technical abilities, in fact, I am assuming you have none.  So if it ever feels like I am insulting your intelligence or speaking down to you, I am not!  On the other hand, if I am unclear or confusing at some point, please let me know and I will try to clarify.

 

 

How young is too young?

 

This is perhaps one of the most common questions asked.  How old do I ( or my child ) have to be to get started in game development?  This is a question with an impossible answer as all kids are different.  On the extremely low end of the range ( and using the right tools ), an incredibly motivated 6 year old would probably be able to have some success.  On the other range of the spectrum, a typical 12 year old should have the educational foundation and mental abilities to succeed.  The actual age is bound to be somewhere in the middle.

 

There are a few critical things to be aware of up front. 

 

The first is motivation.  Motivation is more likely to be the biggest hurdle to success, not mental ability.  If your child absolutely loves creating stuff ( loving to play video games is massively different than loving to create video games ) and is willing to trial and error, they are perfect for game development!

 

The second is managing expectations.  This is where we lose the most potential game developers out there, regardless to age.  Game development doesn’t have to be exceptionally hard, but it is certainly complex.  Your child is not going to be creating massive modern games like Call Of Duty or NHL any time soon.  Nor are they going to create an MMO ( online game like World of Warcraft ).  They need to start small, very small and work their way up from there.

 

A key way to put it is, if your child’s mindset is “I am going to create the next Minecraft”, they are going to fail and fail hard.  On the other hand, if their mindset is “I am going to create the next Minecraft, eventually”, they have perhaps the perfect mentality to succeed.  Knowing the difference there is critical.  Like almost any other skill, you need to start small and build on your successes.  Starting too big will just result in failure and frustration.  For the record, I believe I was about 8 when I started programming using Atari BASIC.

 

 

What is Game Development anyways?

 

This section is going to get slightly more technical, but not overly so.  Game Development is an umbrella term, it includes many different skills all coming together to create a greater whole.  Think about Game Development like you would an car maker.  There is no single skill involved in making a car, instead you have engineers, graphic designers, manufacturers, quality assurance and more all coming together to make a car.  In the case of a game however, it’s still possible for all of these different tasks to be performed by a single person.  There are a number of highly successful games out there that were written, drawn and scored by the same person.  It is important to realize though, this generally isn’t the case.  Basically what I am saying is game development isn't a single task, it’s multiple.  While your child may really enjoy one part, they may dislike another part.  It’s also important when looking at what tools to use to see if they come with art or sound examples to get your child started, so they don’t have to do everything all at once.

 

If you look at a modern game’s credits, you will literally see hundreds of different names and job titles contributed to the project.  When just getting started however, there are really only two tasks to focus on. Creating the game and creating the stuff that goes in the game.

 

Let’s look at the board game Monopoly as an example.  Two major sets of skills went in to making that game.  First you had to create the game…  design the board layout, make the dice rules, write up all the game cards, etc.  Then you had to create the contents of the games, the pictures that went on the board, the drawings on each card, the little plastic houses, etc.

 

In video games, it’s really no different.  You have the task of creating the game, generally called programming and the task of creating stuff to populate your game, be it art, animation or music/sound.  These skills are completely different but are generally required for a game.  This actual tutorial is going to focus mostly on programming, when a child is interested in game development, this is generally what they mean.  A child interested in being a game artist for example, has probably already got their face buried in a notebook, sketching away!  This by the way is the perfect approach for them too, as the difference between “an artist” and a “game artist” is miniscule.  If you do however want to explore computer art for games a bit closer, read this guide.

 

 

What is Programming?

 

So, chances when you are talking about game development you are actually talking about game programming.  What is programming?  The simplest definition I can give is programming is the art of telling the computer what to do.  In the case of game programming, this means doing stuff like “when the user pushes the UP arrow do this” or “when player health equals 0, draw that”.

 

Now how you program games, that’s a much trickier conversation and one of the biggest things that you will struggle with.  Perhaps more importantly, it’s the thing that is going to be most dependent on your child.  We don’t all think the same way and we don’t all express ideas the same.  In some cases a child might take to one particular style while a completely different child would possibly despise it. 

 

For the most part for game programming there are three different ways to tell the computer what to do ( and often a combination of all 3 ):

 

Visually – this is a very common approach for beginners and for game development in general ( Unreal Engine 4, one of the most commonly used commercial game technologies has a Visual scripting interface called Blueprint for example ).  In Visual programming languages you generally drag and drop to draw your game screen, then wire it all together in a flow chart like experience  Basically it’s the programming equivalent of creating a flow chart.  If your child is a visual thinker, this may be the best route for them.

 

Here is an example of a Visual game development tool, Construct:

 

Scripting Languages – With scripting languages you tell a computer what to do using small text files.  You often still draw your game using a visual editor like the picture above, but when actually telling the computer what to do, instead of filling in text boxes or creating flow charts, you use code.

 

Here is an example of the LUA scripting language, using a 2D game library named LÖVE:

image

This little bit of text tells to computer to load an image with the filename “whale.png” and then to draw it on screen.

 

Traditional Programming Languages – Finally a lot of game development is done in traditional programming languages.  Common names include C++, Java, C# and more.  I should start straight away by saying, I do not recommend young programmers start by using a traditional or more accurately, a compiled programming language for several reasons.

 

The big question you may have is, what’s the difference between a scripting and compiled programming language?  A lot of it is technical and beyond the scope of this article but most of it comes down to complexity.  Dealing with a compiled language leaves you dealing with a number of things you simply don’t have to worry about with scripting languages.  Things like compiling ( the act of turning the text you write into something the computer can understand ), linking ( can’t easily explain this one ) and more. 

 

Perhaps more importantly, it’s purpose.  Scripting languages are generally much more focused in what they do and are designed to make things easier for the developer.  Put in the simplest terms, scripting languages are generally a lot easier to learn and use.  If you do want to learn more about traditional programming languages, you can read this guide.  It is a much more technical guide than this one.  If your child is in their teens, this may be an appropriate place to start.  That of course isn’t to say that teenagers ( and older ) are too old for the stuff recommended below.

 

In the end you will often find game development tools offer both a visual system and a scripting language, where much of the game is created using drag and drop but portions can be controlled using a scripting language.

 

 

IDE, Library, what???

 

OK, one last topic to cover before we get into it.  There are a bunch of terms and expressions that get thrown around that might be confusing.  I am going to quickly cover some of them.

 

Language – This is the programming language used.  Just like we used English, Spanish, German etc to talk to each other, we use different languages to talk to computers.  In the example above the programming language was Lua.

IDE – Integrated Development Environment.  This is a bundling of a number of tasks all into a single application.  Not all suggestions will have an IDE, meaning you need to use different programs to do different things.  Generally an IDE includes a text editor, a programming language and various tools all in a single spot.

Library – Think of a library like someone doing a bunch of work for you.  Generally even the “simple stuff” isn’t actually part of the language, things like drawing on the screen.  Instead people write that stuff and make it available to you as libraries.  In some cases, like GameMaker or Construct, it’s all bundled together for you.  In other cases, like Lua, you pick a library to go with the programming language.  Each approach has advantages and disadvantages.  For example, Gamemaker bundling everything together makes life easier to get started, but with Lua, if they don’t like a particular library, they can simply use a different one.

Sprite – A sprite is a graphic used in a game, for example the player.  A sprite can be a single image or could contain multiple for animations.  The exact meaning of a Sprite changes from engine to engine, but is always a visible thing in the game that moves.  If you’ve played Super Mario Brothers, Mario, the turtles, fireballs, etc… would be considered sprites.  The world however, such as pipes and the sky, would not generally be considered sprites.

HTML 5 – This one can get a bit confusing.  HTML5 is the most current version of HTML ( Hyper Text Markup Language ) which is the language of the web.  When you load a webpage in your browser or phone, generally it’s an HTML document that you are looking at.  The confusing part is, HTML5 is actually an umbrella term for a number of technologies that work together to make the web work.  Those include HTML itself, which is a language that describes the contents of a webpage, CSS which is another language that describes how a webpage should look, and finally JavaScript, which is a scripting language that controls the logic.  People often use the terms HTML, HTML5 and JavaScript interchangeably, although this isn’t technically true.  HTML5 can be used to create games and doesn’t have to be run in a web browser.

Debugger – When your game doesn’t run correctly, it can be tricky to figure out why.  Some packages ship with something called a debugger, which is a tool to help you identify problems or “bugs” in your game.  It is a somewhat advanced feature for beginners, but at the point you need one, a debugger can be invaluable.  For additional information on debugging click here, although advanced warning, that is a highly technical article.

 

 

 

Kid Friendly Game Development Options

 

Now after all of that we get to the meat of the article… the actual suggestions for development tools to introduce your child to the world of game development.  This is by no means an all inclusive list!  For each example I will list what’s included, an example of how it works, positives and negatives, the costs if any and links to books available, if applicable.  One last very important thing to note…  any of these options is a valid one, there really isn’t a single ‘best” choice.  Tailor your decision to best match your kids interests.  If you first choice doesn’t work out, try a different one.

 

The following list is in no particular order.

 

Scratch

 

http://scratch.mit.edu/

Overview:

Scratch is an MIT backed project aimed at teaching kids aged 8 to 16 to learn how to program.  There is a massive community built around Scratch, which has been around since 2006.  There is a special focus on being family friendly.  Scratch is run entirely in the web browser, you simply go to the web page and start programming.  If you want to save your work, you need to register, but it’s a simply form and doesn’t even email you for verification.

 

Scratch is firmly in the visual programming languages category.  Your child works by dragging actors onto a scene, then controls them using Lego-like programming blocks.  The blocks are a good parallel to actual programming language structure, so if they switch to scripting or traditional programming, it will make immediate sense.  There is a good amount of documentation available and you can find literally thousands of sample scratch programs to learn from.

 

Perhaps the most valuable part of scratch is it comes preloaded with all kinds of content for your child to get started with.  However it also has the ability to import graphics and audio you create yourself or get from the community, allow an easy transition between programming and making game assets.

 

Screenshots:

Scratch running in Chrome:

image

 

Loading a new Sprite

image

 

Programming in Scratch:

image

The above is a script attached to the blue dog.  It’s in two parts, first is when the Green flag ( Go ) is clicked.  It makes the dog visible, moves to a certain position on screen, then moves by one step over and over.  The other waits until it gets the collide message from the other dog, when it does it goes back to the starting position, changes the scene then hides itself.  Each Sprite has it’s own script.  The programming blocks are drag and dropped from the programming palate:

 

The Programming Palate:

image

These are the blocks you use to program in Scratch.  Above are the “Looks” options.  As you can see, there are a number of different categories to choose from.

Includes or Alternatives:

Scratch is an all in one solution, so you need no other tools to work in Scratch.  It also ships with a large variety of sample scenes, backgrounds and sounds to start with.

Costs:

Scratch is completely free and run by sponsorship donations.

Books:

 

Comments:

Scratch also makes an iPad application called ScratchJr which is aimed at children 5 to 8.  It is also completely free.  Since there is nothing to buy, or download and you don’t even have to register to try Scratch, it is probably the easiest option to try out in this list.

 



 

 

Construct 2

 

https://www.scirra.com/

 

Overview:

Construct2 is another visual programming based game engine.  You create games in Construct2 using a drag and drop interface and control logic using a flow chart like event system.  If the functionality you need isn’t available in Construct2, you can create your own plugins using JavaScript, although this is certainly an advanced feature and is strictly optional, Construct2 is meant to be controlled using the event system.  The ultimate output of Construct2 is HTML5, which can be exported to run on a number of platforms such as mobile ( Android, iOS, Windows Mobile ), browsers and desktop.

 

Construct2 is a great deal more complex than Scratch, which has a two fold impact.  First, Construct certainly has a higher learning curve than Scratch, so it isn’t suitable for younger children and does not take a teaching approach.  On the other hand, it is meant to provide an easy to learn tool capable of creating professional games, instead of for learning.  This means there is a lot more runway before your child runs into any limitations.  There are many professionally shipped games that were created in Construct 2. 

 

There is a good deal of documentation available, including a complete references and a PDF manual available for download.  There is a very active community and strong forum for support.

 

Construct is an application installed on your computer.  Construct requires a computer running Windows.  There is no Mac option currently available.

 

Screenshot:

Construct 2 Main Window:

image

 

Event Sheets

image

This is the primary way of programming a Construct 2 game.  The example above is part of the code controlling how the player responds to input, taken from one of the included samples that shows creating a simple shooting game.

Behaviors

image

Behaviors allow you add quickly add predefined behavior to a game object.

Integrated Image Editor:

image

 

Includes or Alternatives:

Construct 2 is an all in one solution that contains everything you need to get started.  Out of the box however it does not contain a ton of content to get started with.  They do however have a free asset pack available for download. ( Warning, that is a direct download link.  Click it and the 38mb archive of assets will start downloading ).  If you move beyond the free version, you get more assets included.

If you do get into creating plugins, you will need to download the JavaScript SDK, which is available for free.  In this case you will need to provide your own text editing environment, Construct does not include one.

Costs:

Construct2 has tiered pricing.

  • There is a free version available to download.  The free version is only able to create games that run in your browser.  It also includes less bundled assets and has a number of limitations on the complexity of game that can be created.  This limits shouldn’t be too much of a problem at least initially.
  • The Personal Edition is currently 129USD, is able to create Desktop, iPhone and Android games and includes much more bundled assets like sounds, songs and sprites.
  • Finally, there is a Business Edition, which is exactly the same as Personal Edition, except it costs more and is required if you make more than 5,000USD from your Construct2 games.  Basically if you have this problem, it’s a good problem to have!

 

Books:

 

Comments:

None

 



 

Game Maker

 

https://www.yoyogames.com/studio

 

Overview:

GameMaker is an all in one game creation system that is a hybrid providing both a visual programming interface, as well as a scripting language, their own proprietary language GML.  GameMaker initially exports to Windows only, but for a fee can also create games for iOS, Android, Web, Windows Phone and more.

 

Programming in GameMaker can be done in a flow chart like manner, similar to Construct2.  It also adds the option of programming in their own scripting language GML.  This is both a plus and a minus.  The ability to program using a Scripting language in addition to the visual system gives the user a great deal of flexibility.  It is however a more complex process.  Since the language is proprietary to GameMaker, if they move to a different environment, a lot of their knowledge will be less useful.  That said, general programming concepts stay pretty much the same from language to language, so this isn’t as big of a problem as it might sound.

 

Other than assets to get started with, GameMaker quite literally ships with everything you might need out of the box, although the quality of the tools varies.  You are able to create graphics, sounds and levels in addition to programming, all in one single application.  GameMaker has been used to make some very successful commercial games such as the original version of Spelunky and Hotline Miami ( not for children ).

 

GameMaker is one of the more complex options on this list and is probably not appropriate for pre-teen level children.  For older children though, it offers a lot of flexibility and a ton of options should they wish to share or sell their games eventually.  Obviously this changes from child to child, so there is no hard set rule.  Just be aware, compared to say Scratch, the difficulty level here is much higher. 

 

Screenshot:

Main Interface:

image

Visual Programming:

image

Scripting:

(Script for firing a bullet)

image

Level Editor:

image

Sprite Editor:

image

Includes or Alternatives:

GameMaker is an all in one solution and contains everything you will need to make a game including code editing, image creation and editing, map designer and more.  It also includes a built in debugger, useful for hunting down problems.  The standard version however comes with very little in the way of included samples to get started with.  In fact, there are none.  However there is a very active community and tons of examples and tutorials available online.  The quality of the materials varies massively and curation by Yoyo Games is lacking, so finding the best starting material can be a bit of a challenge.  For all of the screenshots and code samples in this entry, I used material from this tutorial.

 

Costs:

GameMaker licensing can be a bit confusing, as their pricing structure has changed and not all material is updated.

The version you initially download is heavily restricted by the number of resources and scripts it can support.

You can however update to the Standard edition by simply registering an email address, which will be verified and you will then be sent a product key.

Then there is a “Professional” version for $100 USD that adds functionality for working with other developers ( you will not need at this point ).  The biggest difference is the Professional version can buy additional modules that support exporting to platforms other than Windows.  Each platform is generally $200 USD.  So for example, if you want to export your game to play on Android and iOS it will cost $500.  $100 for Professional, then $200 for each platform. 

Finally there is a “Master” version, which is basically Pro with all of the different export platforms enabled.  It’s $800USD currently.

For a new developer, the registered Standard edition is most likely good enough.  If you do need Professional, keep an eye on the Steam Store, it is made available for sale quite often.  To add to the confusion, the Standard edition you can download for free is $50USD on Steam.  DO NOT BUY IT!

 

Books:


Comments:

Note, it is not necessary to use the included tools.  For example, if you want to use another graphics program to create sprites, or to import graphics from another source, this is perfectly possible!



 

Lua with LOVE

 

http://www.lua.org/

http://love2d.org/

 

Overview:

Lua is a scripting language, while LOVE is a library for making games ( see the descriptions earlier for definition of a library ).  Lua was a programming language created for non-programmers and has become increasingly popular as a scripting language for commercial games, such as these.  That is one large advantage to choosing this option over say, Gamemaker’s custom scripting language, GML.  Lua is used elsewhere and fairly commonly, so it is a skill that will carry forward very well.    As a language it is fairly simple to learn.

 

LÖVE is the library you use to create games using the Lua programming language.  LÖVE provides pretty much all of the functionality you need to create 2D games including drawing graphics, playing sound, controlling input, loading files, etc. 

 

LÖVE and Lua isn’t a turn key solution like some of the others however, you still need a text editor to create and edit your scripts, a drawing program for creating art, and audio programming for recording sounds, a map maker for creating maps, etc.  Fortunately all of these things are freely available and I have recommendations below.  You do however have to download each one separately.  LÖVE however comes with no assets like graphics or sounds to get started, but sites like Open Game Art and FreeSound can help you get started.  It is however, yet another thing you have to locate and download.

 

The biggest negative about LOVE is the lack of platform support.  Currently LOVE can only create games for computers, although mobile targets are in the works.

 

Screenshot

Sample Lua/LOVE Code:

image

Zerobrane Studio:

image

Includes or Alternatives:

The LOVE library contains Lua, so all you need to get started is here with the getting started documentation here.  However that just gives you Lua and LOVE and nothing else.  You still need a text editor to create your code, plus art and sound programs.

 

For straight text editing, two very popular choices are Notepad++ and Sublime Text.

However, for Lua development I would recommend ZeroBrane Studio which is a more integrated development environment (IDE) that allows things like code suggestions and debugging.  Oh, plus it’s free, which is nice.

For art creation, Paint.NET, GIMP and Inkscape are three very popular free options, the last two however have a pretty hefty learning curve.

For creating levels and maps, Tiled is a very popular and free choice.

 

On the alternatives front, LUA is the scripting language for a number of popular game development tools including Corona, Gideros and Marmalade Quick.  None are as easy to learn as LOVE however, which is why I recommend LOVE over all.  They do however illustrate how learning Lua is a skill that transfers well to other projects.

 

Costs:

Both Lua and LOVE are free.  ZeroBrane is a pay way you like product.

 

Books:

Only one of these books is specifically about LOVE programming.

Lua also have a free reference manual available online.


Comments:

The name of the library is actually LÖVE with an umlaut over the O.  While cute, coupled with the commonness of the word love makes searching for help incredibly annoying.  When using Google, always add “lua” to search expressions.



 

Python with PyGame

 

https://www.python.org/

http://www.pygame.org/news.html

 

Overview:

Like the Lua and LÖVE option, this is a programming language and game library combination.  Very similar to the LÖVE library, PyGame is a very beginner friendly library.  Python is the programming language used in this pairing.  Python is a popular scripting language, although less so in game development.  It is an extremely popular language in the world of 3D graphics, such as at Pixar.   It is also quite commonly used by IT professionals to automate tasks, so even outside game development, Python can be a very valuable skill.  Python has been used to make several games.

 

PyGame also provides most of the common functionality you would expect in a game such as audio, input and graphics.  You also need to provide your own text editor, graphics, sounds, etc.  However unlike LÖVE, PyGame does ship with several examples and some sample assets to get started with.

 

Screenshot:

Python Code in PyCharm

image

Includes or Alternatives:

See the recommendations for LÖVE above, most of the same tools can be used.

ZeroBrane studio however is not an option for Python.  I would personally recommend checking out PyCharm, which has a free version available.  It is however a somewhat complicated editor.  Of course, you can still use whatever text editor you would like, such as the earlier recommendations of Notepad++ or Sublime Text.

 

Costs:

Python and PyGame are both free.  PyCharm is available in a free version.

Books:


Comments:

Python is a more complicated language than Lua, so its is recommended only for older children.  On the other hand, programming in Python is also much closer to programming in traditional languages, so the experience of learning Python will be closest to what professional programming generally feels like.

Sadly, there are two versions of Python, something that has plagued the language for a very long time.  Most of the time you want to use the 2.x version of the language.



 

HTML5 with various

 

http://www.gamefromscratch.com/page/Links-of-interest-for-HTML5-game-developers.aspx

Overview:

HTML5 is a somewhat confusing term these days.  Basically HTML is the language of web browsers while Javascript is the language that enables HTML to do stuff.  With each generation of web browser, the ability to create games has gotten more and more impressive.

 

Javascript is an interesting proposition for learning with as your kids probably already have experience in using a web browser.  Then can simply open a text file, type some code, save and load in the webpage and play.  It’s a very nice feedback loop.  Unfortunately there are some downsides here too.  While a pretty straight forward programming language, Javascript has some horrible flaws that make it hard to recommend to a complete beginner.  On top, each browser has tons of flaws, that also add a layer of complication on top.  Finally there are just so many options when it comes to HTML game development, unlike Lua or Python, that making a recommendation could actually take another article even longer than this one!

 

If you child is interested in working on HTML5 games, it is a good option to persue with the right library.  Two very good options, that provide game functionality and deal with some of the browser lunacy are Phaser and CreateJS, but there are literally hundreds of options.  Both of those libraries are straight forward, well documented and commonly used.

 

Like Python and Lua, HTML5 is not an integrated solution, so you need to provide your own text editor, graphics, etc.  However, pretty much every modern browser has build in tools to make development easier.



 

Stencyl

 

http://www.stencyl.com/

 

Overview:

Stencyl is a visually programmed game creation kit that bills itself as “the quickest and easiest way to make games”, which may actually be true!  In functionality it is very similar to Construct2, you program by drawing out your scene, then adding behaviors visually.  It is an all in one solution with an integrated image editor, although you can always import assets created in external tools.  There is no way to script in Stencyl, although you can create extensions using a programming language called Haxe, if there is functionality you need that is not available in Stencyl.  This however is advanced functionality and is probably beyond your child’s current ability level.  You can however download pre-made extensions from the marketplace.

 

Stencyl runs on Windows, Linux and Mac and by default can only create web (Flash) applications.  The ability to target other platforms like desktop computers (outside their browser), as well as iOS and Android is available for a cost (see below).  While it doesn’t ship with a ton of assets, it does make them very easily available.  In addition the help available online is very good.

 

Screenshot:

Stencyl:

image

Defining Behaviors:

image

Level Editing:

image

Program Flow:

image

Includes or Alternatives:

This is a pretty all in one solution.  Unless you delve into Haxe extension programming, basically everything is here with the initial download, or is linked directly from inside the application.

Costs:

Stencyl is available for free, but limited to applications that run in Flash, either in the integrated player or your browser.  Published games will have a Stencyl splashscreen when they load.

For $99, there is Studio that enables you to target desktop computers outside of the Flash player.  The splashscreen is removed in this version.

For $199, you gain the ability to target iOS and Android.

Books:

     

Comments:

None



 

Lego Mindstorm

 

http://www.lego.com/en-us/mindstorms

 

Overview:

Right off the top let me just say, this stuff is expensive Name Your Link'>Name Your Link'>really expensive.  However if your child shows an interest in robotics or is an avid Lego fan, this can be a very good introduction to programming.  Mindstorm Lego is basically a simple robot creation kit using lego.  The key part is it ships with a programmable piece that enables you to program your robot’s behavior.  Mindstorm enables a nice progression, your child can start by building in Lego, then start controlling the robot using the desktop or iPad application, then graduate to actually programming logic.

 

Lego Mindstorm enables you to simply control your creations, or program them using the EV3 software, a flow chart like process.  They do however make tools available allowing you to get as low leveled as you want to. 

 

Even though it’s somewhat off topic, I mention Mindstorm because it can be an ideal introduction to more (literally) hands on children to the concepts of programming.  Literally being able to see cause and effect in the real world can be very valuable.

 

Screenshot:

Programming Mindstorm:

mindstormProg

A Mindstorm robot assembled:

LEGO Mindstorm robot

Includes or Alternatives:

N/A

Costs:

Name Your Link'>Name Your Link'>Lots!

Books:

EBooks of the manual ( pdf link ) and teaching guide ( pdf link ) are available online.


Comments:

This is pushing the definition of “game programming”, but certainly is a very tactile introduction to many of the same skills that go into game development.  Also I have to say, had my parents purchased this for me as I child I would have considered nominating them for parent of the year awards.  When my daughter gets a bit older I am certainly buying this, but then, is it for her, or me? :)

 



 

Honourable Mentions

 

All lists must end at some point, and this one is no exception.  The following are other recommendations I have for parents looking to get their kids into game programming, but for whatever reason didn’t make the main list.  If nothing above appeals to you, be sure to check some of these options out.

 

Minecraft Modding

If your kids play games, there is probably a pretty good chance you have already been exposed to Minecraft.  Modding is the act of modifying an existing game and Minecraft happens to be a very popular game to mod.  Modifying an existing game can often be a great way, or at least motivation, for learning programming.  There is a HUGE community of people that mod Minecraft.  The downside is, it’s done in the Java programming language and it certainly isn’t suitable for young children.  If your child is very interested in Minecraft though, this could be a good approach to take.  You can learn more here.

 

GameSalad

http://www.gamesalad.com/

GameSalad is another visual game creation kit in the veins of Stencyl and Construct2 mentioned above.  It has been used to create professional games, there is a free version available as well as paid versions for other targeting other platforms.  I personally have no experience with GameSalad.

 

Codea

twolivesleft.com/Codea/

Codea is an iPad application for creating games on the iPad.  It currently costs $10USD.  It uses the Lua programming language and provides it’s own library for creating games that is very easy to learn.  It comes with code editing tools, debugger and tools to hook up with your computer.  You can later hook it up to a Mac and actually create a game for publishing.  However, typing code on an iPad keyboard is extremely unfun, so a bluetooth keyboard is pretty much essential.  It does however come with tons of examples and is actually a great option for a young developer who has an iPad, especially if that’s all they have.

 

Kodu or Project Spark

http://worlds.kodugamelab.com/browse

or

http://www.projectspark.com/#home

This is a game that is about creating games.  Basically it’s a game you can modify to do just about anything.  Kodu is a visual programming language created by Microsoft.  Project Spark is a modified version of Kodu being released shortly for the XBox One console.  It’s pretty far from normal game programming, but many of the concepts ( and the end result! ) are very similar.

 

Code Combat

http://codecombat.com/

Code combat is an interesting concept.  It’s a web based game where you control your character through programming.  As you progress in the game, it teaches harder concepts.  Basically you learn to program while playing a game.  It was originally created to teach Javascript, but has since added a number of other languages.  I believe it is completely free, so you’ve got nothing to lose by trying.

 

Alice

http://www.alice.org/index.php

Alice is a integrated programming solution designed to teach programming.  In their own words:

Alice is an innovative 3D programming environment that makes it easy to create an animation for telling a story, playing an interactive game, or a video to share on the web. Alice is a freely available teaching tool designed to be a student's first exposure to object-oriented programming. It allows students to learn fundamental programming concepts in the context of creating animated movies and simple video games. In Alice, 3-D objects (e.g., people, animals, and vehicles) populate a virtual world and students create a program to animate the objects.

Alice is maintained by Carnegie Mellon university and is completely free.

 

RPGMAKER

http://www.rpgmakerweb.com/

RPGMaker Ace is a product similar to GameMaker specifically for creating one type of games, Role Playing Games, generally along the Japanese style.  Their tagline is literally “Simple enough for a child; powerful enough for a developer.”  There are some commerically created games available that were written using RPGMaker.  If your child is really in to this style of game, RPGMaker could be a great introduction to game programming.  RPGMaker is $70, although quite often on sale on Steam.  Ironically enough, as I write this, it is on sale for 75% off.

 

 

Conclusion

 

Of course I only scratched the surface of the options available, but I think I got the majority of options in that list.  If you think there is something else I should have put in this document, let me know!  I tried to make this clear to people of all technical levels, but no doubt I’ve made mistakes.  If I lost you somewhere, please let me know and I will try to clarify.  The most important thing to remember, all children are different, so one approach that works for one child may fail with another.  Pick the option above that you think most fits with your child's personality, but if it doesn’t seem to be a good fit, remember there’s a dozen other options!

 

I hope that was useful.  Good luck.

Programming, General, Design, Art , ,

12. September 2014

 

 

In my previous Phaser tutorial on particles I used a sprite sheet to provide particles in one of the examples, then realized I hadn’t covered how to actually use a sprite sheet yet, oops!  So this tutorial is going to correct that oversight.  A spritesheet ( also known as a texture atlas ), is simply a collection of images together in a single image file.  Loading a single file into memory is often more efficient than loading dozens on small images.  It’s also generally easier from a resource management perspective.

 

Let’s take a look using the texture I used for the particle example.  It’s a seamless animation of a robin in flight that I downloaded from here.  Here is a small version of the image:

robin-782x1024

 

Now imagine the above image as a 5x5 grid of images.  This gives 22 240x314 bird images and 3 empty spaces.  Now let’s look at using that image to create an animation.

 

/// <reference path="phaser.d.ts"/>
class SimpleGame {
    game: Phaser.Game;
    bird: Phaser.Sprite;

    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload:
            this.preload, render: this.render
        });
    }
    preload() {
        // Load the spritesheet containing the frames of animation of our bird
        // The cells of animation are 240x314 and there are 22 of them
        this.game.load.spritesheet("ss", "robin.png", 240, 314, 22);
    }
    render() {
    }
    create() {
        this.bird = this.game.add.sprite(0, 0, "ss", 0);
        // Create an animation using all available frames
        this.bird.animations.add("fly");
        // Play the animation we just created at 10fps, looping forever
        this.bird.play("fly", 10, true);
    }
}

window.onload = () => {
    var game = new SimpleGame();
};

 

And running:

 

 

 

So I mentioned earlier about a texture atlas.  What is that if not a spritesheet?  Well basically it’s the same thing, but with a  table of contents if you will.  The spritesheet relies entirely on images being the same size in a grid like the above.  A texture atlas on the other hand is more flexible.

 

First is the matter of how to create them.  There are actually several applications capable of creating Phaser compatible texture atlases, but TexturePacker is probably the easiest.  I am not going to go into detail on how to use TexturePacker in this post as I have already done so in the past.  For more information click here.

 

There are a couple things to be aware of that are Phaser specific.  For this example I am going to use the animation I created in my Blender tutorial series.  It’s simply the jet in a barrel roll animation, rendered as individual frames, like so:

 

0005000100020003

 

When choosing your project type, Phaser is not listed.  Instead choose Sparrow/Starling:

image

 

Simply drag and drop your frames on animation then set the following settings:

image

 

Size Constraints does not need to be set to Power of 2, but it’s generally a good idea for performance.

Allow Rotation CANNOT be checked, it will break Phaser.

Trim mode is important for this case, as I want to keep the white spaces so the image size remains the same across all animations.  For animations you will generally want to set this to keep your frames the same size.  For non-animations, it can save a great deal of space not selecting this option.

 

When ready click Publish Sprite Sheet at the top button bar.  This will then save an xml file and a png for you to use.  I called mine jet.xml and jet.png, but I am a creative type.

 

Now let’s look at the code for using a texture atlas instead of a sprite sheet… a bit of a warning, it’s awfully same-y.

 

/// <reference path="phaser.d.ts"/>
class SimpleGame {
    game: Phaser.Game;
    jet: Phaser.Sprite;

    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload:
            this.preload, render: this.render
        });
    }
    preload() {
        this.game.load.atlasXML("jet", "jet.png", "jet.xml");
    }
    render() {
    }
    create() {
        this.jet = this.game.add.sprite(0, 0, "jet", 0);
        // Make it bigger so we can see
        this.jet.scale.setMagnitude(3);
        this.jet.animations.add("fly");
        this.jet.animations.play("fly", 15,true);
    }
}

window.onload = () => {
    var game = new SimpleGame();
};

 

And when we run it:

 

 

And that is how you use a spritesheet or texture atlas.

Programming , , , ,

10. September 2014

 

In the previous tutorial part we look at creating about the simplest physics simulation possible in LibGDX and Box2D, a single object affected by gravity.  In this tutorial we are going to take things one step further and apply force, impulses and torque ( and no gravity ) to our physics body.  This part is going to consist of a single large code example.

 

Speaking of which, here it is!

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.*;

public class Physics2 extends ApplicationAdapter implements InputProcessor {
    SpriteBatch batch;
    Sprite sprite;
    Texture img;
    World world;
    Body body;
    Box2DDebugRenderer debugRenderer;
    Matrix4 debugMatrix;
    OrthographicCamera camera;
    
    
    float torque = 0.0f;
    boolean drawSprite = true;
    
    final float PIXELS_TO_METERS = 100f;

    @Override
    public void create() {

        batch = new SpriteBatch();
        img = new Texture("badlogic.jpg");
        sprite = new Sprite(img);

        sprite.setPosition(-sprite.getWidth()/2,-sprite.getHeight()/2);

        world = new World(new Vector2(0, 0f),true);
        
        BodyDef bodyDef = new BodyDef();
        bodyDef.type = BodyDef.BodyType.DynamicBody;
        bodyDef.position.set((sprite.getX() + sprite.getWidth()/2) / 
                             PIXELS_TO_METERS, 
                (sprite.getY() + sprite.getHeight()/2) / PIXELS_TO_METERS);

        body = world.createBody(bodyDef);

        PolygonShape shape = new PolygonShape();
        shape.setAsBox(sprite.getWidth()/2 / PIXELS_TO_METERS, sprite.getHeight()
                       /2 / PIXELS_TO_METERS);

        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = shape;
        fixtureDef.density = 0.1f;

        body.createFixture(fixtureDef);
        shape.dispose();
        
        Gdx.input.setInputProcessor(this);
        
        // Create a Box2DDebugRenderer, this allows us to see the physics 
        simulation controlling the scene
        debugRenderer = new Box2DDebugRenderer();
        camera = new OrthographicCamera(Gdx.graphics.getWidth(),Gdx.graphics.
                 getHeight());
    }

    private float elapsed = 0;
    @Override
    public void render() {
        camera.update();
        // Step the physics simulation forward at a rate of 60hz
        world.step(1f/60f, 6, 2);
        
        // Apply torque to the physics body.  At start this is 0 and will do 
        nothing.  Controlled with [] keys
        // Torque is applied per frame instead of just once
        body.applyTorque(torque,true);
        
        // Set the sprite's position from the updated physics body location
        sprite.setPosition((body.getPosition().x * PIXELS_TO_METERS) - sprite.
                           getWidth()/2 , 
                (body.getPosition().y * PIXELS_TO_METERS) -sprite.getHeight()/2 )
                 ;
        // Ditto for rotation
        sprite.setRotation((float)Math.toDegrees(body.getAngle()));

        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        
        batch.setProjectionMatrix(camera.combined);
        
        // Scale down the sprite batches projection matrix to box2D size
        debugMatrix = batch.getProjectionMatrix().cpy().scale(PIXELS_TO_METERS, 
                      PIXELS_TO_METERS, 0);
        
        batch.begin();
        
        if(drawSprite)
            batch.draw(sprite, sprite.getX(), sprite.getY(),sprite.getOriginX(),
                       sprite.getOriginY(),
                sprite.getWidth(),sprite.getHeight(),sprite.getScaleX(),sprite.
                                getScaleY(),sprite.getRotation());
                        
        batch.end();
        
        // Now render the physics world using our scaled down matrix
        // Note, this is strictly optional and is, as the name suggests, just 
        for debugging purposes
        debugRenderer.render(world, debugMatrix);
    }

    @Override
    public void dispose() {
        img.dispose();
        world.dispose();
    }

    @Override
    public boolean keyDown(int keycode) {
        return false;
    }

    @Override
    public boolean keyUp(int keycode) {
        
        // On right or left arrow set the velocity at a fixed rate in that 
        direction
        if(keycode == Input.Keys.RIGHT) 
            body.setLinearVelocity(1f, 0f);
        if(keycode == Input.Keys.LEFT)
            body.setLinearVelocity(-1f,0f);

        if(keycode == Input.Keys.UP)
            body.applyForceToCenter(0f,10f,true);
        if(keycode == Input.Keys.DOWN)
            body.applyForceToCenter(0f, -10f, true);
        
        // On brackets ( [ ] ) apply torque, either clock or counterclockwise
        if(keycode == Input.Keys.RIGHT_BRACKET)
            torque += 0.1f;
        if(keycode == Input.Keys.LEFT_BRACKET)
            torque -= 0.1f;
        
        // Remove the torque using backslash /
        if(keycode == Input.Keys.BACKSLASH)
            torque = 0.0f;
        
        // If user hits spacebar, reset everything back to normal
        if(keycode == Input.Keys.SPACE) {
            body.setLinearVelocity(0f, 0f);
            body.setAngularVelocity(0f);
            torque = 0f;
            sprite.setPosition(0f,0f);
            body.setTransform(0f,0f,0f);
        }
        
        // The ESC key toggles the visibility of the sprite allow user to see 
        physics debug info
        if(keycode == Input.Keys.ESCAPE)
            drawSprite = !drawSprite;

        return true;
    }

    @Override
    public boolean keyTyped(char character) {
        return false;
    }

    
    // On touch we apply force from the direction of the users touch.
    // This could result in the object "spinning"
    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        body.applyForce(1f,1f,screenX,screenY,true);
        //body.applyTorque(0.4f,true);
        return true;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        return false;
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        return false;
    }

    @Override
    public boolean mouseMoved(int screenX, int screenY) {
        return false;
    }

    @Override
    public boolean scrolled(int amount) {
        return false;
    }
}

 

Here it is running in your browser.  You may have to click the application to give it focus.

 

 

You can control it using the following controls:

  • Left and Right Arrow:  Apply impulse along X axis
  • Up and Down Arrow: Apply force along Y axis.
  • [ and ]: Apply torque
  • \: Set torque to 0
  • SPACEBAR or '2': Reset all
  • Click, apply force from point of click
  • ESC or '1' toggles display of the sprite graphic on and off

EDIT: OK, several keyboard combo’s do not work correctly in an iframe.  To fully interact with the above application click here to open it in it’s own window:

 

 

You may notice applying force will cause your object to not just move, but also rotate, depending on the angle you click.  You can also offset this force by clicking in the mirrored opposite side.  Also notice that applying impulse moves the object along at a constant rate, and applying the opposite impulse will bring the object to a standstill.  Hitting left or right multiple times however will not increase the speed.  However, applying force, by hitting up or down will cause it to get faster for each time you add force.  This is one of the major differences between impulse and force.  Torque works very similar,  to stop it from spinning you need to apply the appropriate amount of torque from the opposite direction.  Even setting torque to 0 will have little effect due to momentum.

 

Now let’s take a look at a few key concepts here.  First thing you should notice is:

final float PIXELS_TO_METERS = 100f;

 

Well, remember when I said in the last part that the units you use don’t really matter as long as you are consistent?  Well, let’s reclassify that as “kinda true”.  Or, completely true, but not really!  Clear now?

 

Truth of the matter is, Box2d is “tuned” to work in MKS units, which to you non-Canadian/European readers translates to Meters, Kilograms and Seconds.  Don’t get me wrong, you can still work in lbs, miles or parsecs, but you are going to fight with Box2D a bit.  Additionally, this blurb from Box2D documentation is also pretty important:

 

Box2D is tuned for MKS units. Keep the size of moving objects roughly between 0.1 and 10 meters. You'll need to use some scaling system when you render your environment and actors. The Box2D testbed does this by using an OpenGL viewport transform. DO NOT USE PIXELS.

 

So, what did I use in the prior example?  Yeah… pixels.  In reality though, when dealing with gravity only it really doesn’t matter all that much.  Once terminal velocity kicks in, all things fall at the same rate anyways.

 

But… now that we are going to working with forces and such, suddenly it becomes very important not to use pixels, and let me quickly explain why.  Consider when we create our physics object, we define it’s shape and density, like so:

 

shape.setAsBox(sprite.getWidth()/2, sprite.getHeight()/2);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = 1f;

 

Our sprite is an image 256x256 in size.  Our density, which by the way is by default kg/ms2 is 1.  As a direct result, in our simulation or sprite has a default mass of…  65,536kg.  Hmmm, that’s kind of heavy and is going to require a hell of a lot of force to move!  If you are trying out box2d and you are finding that force isn’t working as you’d expect, take a look at your units, that’s the most likely culprit.  A rather easy work around is to use one set of coordinates in Box2D and translate to and from pixels to meters and back again.  For that we use:

 

When translating to box coordinates, divide by this value, when translating back, multiply by it.  Basically what we are saying is 1 meter in box2d represents 100 pixels in our game.  So for our 256x256 image, in box it is roughly 2.5m x 2.5m instead of 250x250!  You will notice however that this isn’t the only translation we do:

 

To box2d:

        bodyDef.position.set((sprite.getX() + sprite.getWidth()/2) / 
                             PIXELS_TO_METERS, 
                (sprite.getY() + sprite.getHeight()/2) / PIXELS_TO_METERS);

From box2d:

        sprite.setPosition((body.getPosition().x * PIXELS_TO_METERS) - sprite.
                           getWidth()/2 , 
                (body.getPosition().y * PIXELS_TO_METERS) -sprite.getHeight()/2 )
                 ;

 

There is another calculation in there, each way we are either adding or subtracting half the sprites width and height.  This is due to box2d and LibGDX using two different coordinate systems.  In LibGDX, the sprite’s origin is it’s bottom left corner, while in box2d, it’s the middle.  You may be thinking, hey, I’ll just set the origin.  That wont do you any good actually, as in LibGDX this is only used for scaling and rotation.  So, when moving between the two coordinate systems be mindful of the different origins.

 

Otherwise the code is fairly straight forward.  From playing around with the application the difference between force and impulse is easy to see.  You can think of Force like the action of pushing someone.  It will require a higher value as you have to overcome their inertia, however pushing someone again will cause them to accelerate faster and faster.  Impulse on the other hand can be though of like the acceleration in a car.  A car with an impulse of 50km, moves along steadily at a rate of 50km.  The only way to change speeds would be to change impulse, the values would not be cumulative.  However, if another car rear ended you ( FORCE! ), you can certainly see an increase in velocity! ;)

 

Torque on the other hand is a measure of rotational force.  Unlike force and impulse, in Box2D, torque needs to be applied each frame.  Stop applying torque each frame and things stop, um, torqueing.  Finally, in terms of motion, the touch handler applies force from a given direction.  When the user presses up or down, the force was applied to the center of the object equally.  However, when the user touches or clicks the screen, the force is applied from the direction of contact.  Think just like real life, if you push a glass of beer at it’s center point, it will slide across the table.  However, push it at the top and it will probably tip.  You do have the option of turning a bodies rotation off if so required.

 

You can also set values direction, like I did when the user hits the space bar.  I set the position, torque, rotation and speed of the object back to zero.  This kind of stuff REALLY screws with Box2D though, so if you don’t have to, don’t directly manipulate values, instead work through forces.  In a simple simulation like this, its not really a big deal.

 

Finally you may notice I enabled the Box2DDebugRenderer.  In the running example, hit the ESC key ( you may have to click to give keyboard focus ) and you will see a rectangle in place of the sprite.  This is an internal representation of the physics body in box2d.  When debugging physics problems, this renderer can be invaluable.  Not however that we had to modify it’s projection matrix to correspond with our 100pixel per meter scaling factor.

 

Now that we’ve got things moving, in the next part we will look at what happens when they collide.

Programming ,

8. September 2014

 

The following is a guest tutorial by Avetis showing how to use LibGDX and Overlap2D to create an Angry Birds like game.  Overlap2D is a level and UI editor handy for separating game coding from content creation.  Keep in mind, Overlap2D is fairly young, currently at 0.0.4 version. Now, on with the tutorial!

 



Making Flappy Bird with Overlap2D – Overlappy Tutorial

 

 

Agenda


In this tutorial we are going to create a FlappyBird clone game (for learning purposes only) using Java, LibGDX framework and accelerate it all by moving our UI, Level, and Asset management into Overlap2D Editor. One thing I figured while coding is that you can’t make a quick tutorial about a flappy bird clone, ever. It’s going to be long if we want details. It is easier though to use the explain approach instead of step by step guide.  So I am going to share all the sources and resources, and then go with you through setting this all up, show how things work, and hopefully this all will make sense.

 

Prerequisites


Java knowledge, basic LibGDX experience, computer, time. Make sure you use latest Overlap2D editor and runtimes (v 0.0.4 or higher)

Get latest LibGDX project setup here: http://bitly.com/1i3C7i3 ( Details here )
Get latest Overlap2D editor here: http://overlap2d.com

 

First - Get Game Assets (Resources)


First let’s download the assets. I made a small pack of images I found on the internet with Flappy Bird images, animations and font. You can get it here: http://overlap2d.com/?p=236

 

 

Setting up Your Overlap2D Project

 

Unzip your Overlap2D zip file, and run the Overlap2D.jar.


First things first, you are currently viewing demo project, so go to File and Create New Project. Call it OverlappyBird and then create the scene size, let it be 480 width, 800 in height. It’s a standard small mobile device resolution, and since Flappy Bird is a portrait game, it should be just right. Click Create Project.
You have now created an empty project and it’s ready for setup, now you need to import the assets. Here we have 3 types of assets, first is just image textures, and second is a sprite animation for bird itself, and lastly the TTF font for score label. I have separated them in folders so you can import easily. Click on File, import to library.


First click on “…” button near the import images text field to select your images; locate them, select all. When done click on import and they all will get imported to your assets area on the right middle panel. Then open same the dialog again, and this time find Import Sprite Animations (note: not spine, but sprite) Click on “…” button there and locate bird.atlas file. Click Import, and it will get added to your assets list as well.


Lastly open import dialog again, and import font, by locating ttf file.


Your project setup is ready.

 

Making The Main Scene

 

First let’s see how main scene looks in Overlap2D when it is finished:

 

image


 
I decided to make several layers to have things organized, bg layer for background image that is not moving, default layer for pipes and bird itself, ground layer for moving the ground that is covering pipes, ui layer for “get ready” popups and score labels, and finally dlg layer for end game dialog. The reason I am not putting dialog inside ui layer is that I can position it in its layer correctly, and later hide that layer so it will not intervene with my work.  So, go ahead and create this layers in the order I described from bottom to top. (bg layer goes below them all, and you can rearrange them by drag-and-dropping)


I also recommend you to open my example project (provided with resources). Open it with Overlap2D and see how things are positioned and grouped. (To open a project, click file, open, and then locate .pit file inside project.)


Compose your own project like I did,. Put background on bg layer, and add bird on default layer. Make sure it looks like the picture above.


The ground is going to be a moving part, so we need to have 2 of this near each other for seamless movement. Put two grounds near each other and then group them into composites, like on this picture, do not forget to give identifier to it for later use.


image

 

For the pipes we are going to do the following trick. First of all we are going to put pipes on top of each other with a gap, and convert them into composite, and then add to library to have kind of a prefab for a pipe column. Later in code we are going to pre-load 3 of this because there is never more than 3 columns of pipes visible on screen, so we can re-use the ones that are left of the screen for next pipe iteration.


image


Now some of the pipes are going to vary in position on Y axis. So there are a minimum and maximum values that it should not be below or above. To avoid having this values in code, I just put 2 of pipe columns on screen: one at the lowest point and the other at the highest, and give them identifiers in order to read those values from code later.

 

image

 

Next click on bird in properties box and add 2 custom variables, by clicking on custom variables button. First is jump_speed=400, and second is gravity=1000 (so you can later tweak game from editor not from code)


image

 

Next up, put a “hint” and “get ready” assets convert them into composite as they always go together and give them id to hide show from game. They should go to ui layer.

 

Making Menu Scene

 

This one is easier: click on File, Scenes, Create New Scene, and choose MenuScene as name.


Make sure to put up all things just like on this picture. And note that you should make a composite for ground agai n (as we do not yet share prefabs between the scenes).


Put a Play button as image and give it an id to add listeners later in your code.


Here is how it should look:

 

image

 

Overlap2D Part DONE!


Looks pretty good! Both scenes are set up and ready for some coding. Most importantly your scene and UI are very flexible and code-independent.

 

 

 

Setting up LibGDX Project and Getting Ready to Code:

 

Download the LibGDX setup application and setup an empty project (make sure to have checked box2d and freetype fonts), import it to your eclipse or other IDE, run the desktop app to make sure it works, then strip it from LibGDX picture  and make it just a black screen.


Make sure your desktop launcher has code to specify screen size of 480x800 (config variables in launcher).


We are going to render everything using a simple LibGDX Stage, so the code structure will be the following: GameStage extending Stage that will load all the Overlap2D data and display it; Main class that will be rendering GameStage in its render method.


For all the rest we are going to use iScript functionality of Overlap2D. Let me go a bit in depth for that. Overlap2D runtime provides an interface that you can implement to create a “brain” of any composite item. Basically it is your way of attaching logic to an object. In this example we are going to create 3 iScripts, one is going to get attached to entire mainScreen and be a GameScreenScript with all game logic, other will be MenuScreenScript for menu, and the last one will be BirdScript that we will attach to the bird. It is important to mention that you cannot attach script to an image, or sprite animation, so I have converted bird animation to composite item in order to do it (right click, convert into composite).

 

You can find the full project on my github:  https://github.com/azakhary/OverlappyBird

Here are the well commented sources:

 

OverlappyBird.java

package com.underwater.demo.overflappy;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

/*
 * This is our ApplicationListener the main thing that things start in libGDX
 */
public class OverflappyBird extends ApplicationAdapter {
   
   /*
    * GameStage will be holding both menu and main game
    */
   private GameStage stage;
   
   @Override
   public void create () {
      stage = new GameStage();
   }

   @Override
   public void render () {
      // Clearing the screen before each render
      Gdx.gl.glClearColor(0, 0, 0, 1);
      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
      
      // calling stage act method and passing delta time passed since last call
      stage.act(Gdx.graphics.getDeltaTime());
      // drawing all actors
      stage.draw();
      
   }
}

GameStage.java

package com.underwater.demo.overflappy;

import java.io.File;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.uwsoft.editor.renderer.DefaultAssetManager;
import com.uwsoft.editor.renderer.SceneLoader;

/*
 * GameStage 
 */
public class GameStage extends Stage {
   
   // Speed of pixels per second of how fast things move left (required both for 
                                                               menu and the game,
                                                               thus put here)
   public float gameSpeed = 200;

   // Overlap2D  provides this easy asset manager that loads things as they are 
   provided by default when exporting from overlap
   private DefaultAssetManager assetManager;
   
   public GameStage() {
      super();
      
      // Set this is input processor so all actors would be able to listen to 
      touch events
      Gdx.input.setInputProcessor(this);
      
      // Initializing asset manager
      assetManager = new DefaultAssetManager();
      
      // providing the list of sprite animations which is one in this case, to 
      avoid directory listing coding
      assetManager.spriteAnimationNames = new String[1]; assetManager.
                                          spriteAnimationNames[0] = "bird";
      
      // loading assets into memory
      assetManager.loadData();
      
      // Menu goes first
      initMenu();
   }
   
   public void initMenu() {
      clear();
      
      // Creating Scene loader which can load an Overlap2D scene
      SceneLoader menuLoader = new SceneLoader(assetManager);
      
      // loading MenuScene.dt from assets folder
      menuLoader.loadScene(Gdx.files.internal("scenes" + File.separator + 
                           "MenuScene.dt"));
      
      // Initializing iScript MenuSceneScript that will be holding all menu 
      logic, and passing this stage for later use
      MenuScreenScript menuScript = new MenuScreenScript(this);
      
      // adding this script to the root scene of menu which is hold in 
      menuLoader.sceneActor
      menuLoader.sceneActor.addScript(menuScript);
      
      // Adding root actor to stage
      addActor(menuLoader.sceneActor);
      
      
   }
   
   public void initGame() {
      clear();
      
      // Creating Scene loader which can load an Overlap2D scene
      SceneLoader mainLoader = new SceneLoader(assetManager);
      
      // loading MainScene.dt from assets folder
      mainLoader.loadScene(Gdx.files.internal("scenes" + File.separator + 
                           "MainScene.dt"));
      
      // Initializing iScript GameSceneScript that will be holding all game, and 
      passing this stage for later use
      GameScreenScript gameScript = new GameScreenScript(this, mainLoader);
      
      // adding this script to the root scene of game which is hold in 
      mainLoader.sceneActor
      mainLoader.sceneActor.addScript(gameScript);
      
      // Adding root actor to stage
      addActor(mainLoader.sceneActor);
   }

}

GameScreenScript.java

package com.underwater.demo.overflappy;

import java.util.ArrayList;

import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.actions.AddAction;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.uwsoft.editor.renderer.SceneLoader;
import com.uwsoft.editor.renderer.actor.CompositeItem;
import com.uwsoft.editor.renderer.actor.LabelItem;
import com.uwsoft.editor.renderer.script.IScript;

/*
 * iScript for entire game logic
 */
public class GameScreenScript implements IScript {
   
   /*
    * reference to GameStage
    */
   private GameStage stage;
   
   /*
    * Main actor that holds root of game screen
    */
   private CompositeItem game;
   
   // Screen loader reference to be later used to retrieve prefabs from library
   private SceneLoader loader;
   
   // Game over Dialog actor
   private CompositeItem gameOverDlg;
   
   /*
    * this will be holding 2-ground system composite item 
    */
   private CompositeItem groundRotator;
   
   /*
    * Instead of holding bird actor we are going to hold birdscript that will 
    provide all bird logic and methods.
    * Also it will have bird actor inside
    */
   private BirdScript bird;
   
   // Hint Box actor the one that shown in begining of game
   private CompositeItem hintBox;
   
   // some helping booleans
   private boolean gameStarted = false;
   private boolean groundStop = false;
   
   // going to hold what is the possible low and high position for a pipe column
   private float minPipe;
   private float maxPipe;
   
   private int gameScore = 0;
   private LabelItem scoreLbl;
   
   // Going to hold 3 pipes here to reuse as pipe pool
   private ArrayList<CompositeItem> pipes = new ArrayList<CompositeItem>();
   
   public GameScreenScript(GameStage stage, SceneLoader loader) {
      this.stage = stage;
      this.loader = loader;
   }
   
   @Override
   public void init(CompositeItem gameItem) {
      game = gameItem;
      
      gameScore = 0;
      
      // Creating and holding BirdScript that will hold entire bird logic.
      bird = new BirdScript(stage);
      game.getCompositeById("bird").addScript(bird);
      
      groundRotator = game.getCompositeById("groundRotator");
      hintBox = game.getCompositeById("hintBox");
      scoreLbl = game.getLabelById("scoreLbl");
      
      // Adding listeners to listen for taps to make bird jump
      game.addListener(new ClickListener() {
         public boolean touchDown (InputEvent event, float x, float y, int 
                                   pointer, int button) {
            return true;
         }
         public void touchUp (InputEvent event, float x, float y, int pointer, 
                              int button) {
            // screen tap was done
            screenTap();
         }
      });
      
      // Loading min/max positions from level editor
      minPipe = game.getCompositeById("minPipe").getY();
      maxPipe = game.getCompositeById("maxPipe").getY();

      // Retrieving 3 pipe columns from library putting them into array,
      // and adding on screen in minus coordinates so the will becom "availible"
      for(int i = 0;  i < 3; i++) {
         CompositeItem pipe = loader.getLibraryAsActor("pipeGroup");             
         pipe.setX(-pipe.getWidth());        
         game.addItem(pipe);
         
         pipes.add(pipe);
      }
      
      
      // Making sure first pipe will be added not sooner then 3 seconds from now
      game.addAction(Actions.sequence(Actions.delay(3.0f), Actions.run(new 
                     Runnable() {
         
         @Override
         public void run() {
            putPipe();
         }
      })));
      
      // hiding game over dialog
      gameOverDlg = game.getCompositeById("gameOverDlg");
      // it should not listen for taps
      gameOverDlg.setTouchable(Touchable.disabled);
      gameOverDlg.setVisible(false);
   }

   @Override
   public void act(float delta) {
      
      // if game is not yet started or started (but most importantly not ended, 
                                                ground is moving) 
      if(!groundStop) {
         groundRotator.setX(groundRotator.getX() - delta * stage.gameSpeed);     
         if(groundRotator.getX() < -groundRotator.getWidth()/2) groundRotator.
            setX(0);
      }
      
      // if game is started, so first tap fone, then we dhould check for 
      collisions and move pipes
      if(gameStarted) {
         for(int i = 0; i < pipes.size(); i++) {
            // get pipe
            CompositeItem pipe = pipes.get(i);
            
            // move it if it has positive coordinate
            if(pipe.getX() > -pipe.getWidth()) {
               // if pipe was right of thebird, and will now become left of the 
               bird, add to score
               if(pipe.getX() >= bird.getBirdCenter().x && pipe.getX() - delta * 
                  stage.gameSpeed < bird.getBirdCenter().x) {
                  gameScore++;
               }
               pipe.setX(pipe.getX() - delta * stage.gameSpeed);
            }
            
            //check for collision with bird
            collisionCheck();
         }
      }
      
      // update scorel label
      scoreLbl.setText(gameScore+"");
   }
   
   /*
    * Check for bird versus pipe row collision
    */
   private void collisionCheck() {
      // iterate through all 3 pipes
      for(int i = 0; i < pipes.size(); i++) {
         CompositeItem pipe = pipes.get(i);
         
         // to make it easy going to think about bird as circle with 5 radius 
         Vector2 birdPoint = bird.getBirdCenter();
         
         // Is there collision? if yes stop the game and allow bird to fall
         if(birdPoint.x+5 > pipe.getX() && birdPoint.x - 5 < pipe.getX() + pipe.
            getWidth() && (pipe.getY() + 532 > birdPoint.y - 5 || pipe.getY()+
            701 < birdPoint.y + 5)) {
            stopGame(); 
         }
         
         // Did bird hit the ground? not only stop the game but also 
         // disable gravity to keep from further falling, and consider bird dead 
         ( animations stop )
         if(birdPoint.y-5 < groundRotator.getY()+groundRotator.getHeight()) {
            if(!groundStop) {
               stopGame();
            }
            bird.disableGravity();
            bird.getBird().setY(groundRotator.getY()+groundRotator.getHeight()+5)
                         ;
            // killitwithfire
            bird.die();
         }
      }
   }
   
   /*
    * Stops the game
    */
   private void stopGame() {
      gameStarted = false;
      groundStop = true;
      game.clearActions();
      
      // show end game dialog
      showEndDialog();
   }
   
   /*
    * showing end game dialog
    */
   public void showEndDialog() {
      // enabling touch back, showing
      gameOverDlg.setTouchable(Touchable.enabled);
      gameOverDlg.setVisible(true);
      // setting transparency to full
      gameOverDlg.getColor().a = 0;
      // and fading it in
      gameOverDlg.addAction(Actions.fadeIn(0.4f));
      
      // setting play button listener to replay the game
      gameOverDlg.getImageById("playBtn").addListener(new ClickListener() {
         public boolean touchDown (InputEvent event, float x, float y, int 
                                   pointer, int button) {
            return true;
         }
         public void touchUp (InputEvent event, float x, float y, int pointer, 
                              int button) {
            stage.initGame();
         }
      });
   }
   
   /*
    * Called when screen is tapped
    */
   private void screenTap() {
      // if ground is not moving then bird is dead no actin required on tapp
      if(groundStop) return;
      
      // if game started just jump the bird
      if(gameStarted) {
         bird.jump();
      } else {
         // if game is not yet started, start the game and jump the bird
         gameStarted = true;
         hintBox.addAction(Actions.fadeOut(0.3f));
         // and also enable gravity from now on
         bird.enableGravity();
         bird.jump();
      }
   }
   
   /*
    * get's availible pipe
    * availible pipe is any pipe that is left of screen and not visible
    */
   public CompositeItem getAvailablePipe() {
      for(int i = 0; i < pipes.size(); i++) {
         if(pipes.get(i).getX() <= -pipes.get(i).getWidth()) {
            return pipes.get(i);
         }
      }
      
      return null;
   }
   
   /*
    * this is called every X time to put a new pipe on the right
    */
   public void putPipe() { 
      // getting availible pipe
      CompositeItem pipe = getAvailablePipe();
      
      // when you die at bad moment, it can be null sometimes
      if(pipe == null) return;
      
      // put pipe column on the random hight from min to max range
      pipe.setX(stage.getWidth());
      pipe.setY(MathUtils.random(minPipe, maxPipe));
      
      // schedule next pipe to be put in 1.3 seconds
      game.addAction(Actions.sequence(Actions.delay(1.3f), Actions.run(new 
                     Runnable() {
         
         @Override
         public void run() {
            // call itself
            putPipe();
         }
      })));
   }

}

 

MenuScreenScript.java

 

package com.underwater.demo.overflappy;

import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.uwsoft.editor.renderer.actor.CompositeItem;
import com.uwsoft.editor.renderer.actor.ImageItem;
import com.uwsoft.editor.renderer.actor.SpriteAnimation;
import com.uwsoft.editor.renderer.script.IScript;

/*
 * iScript for menu logic
 */
public class MenuScreenScript implements IScript {
   
   /*
    * reference to GameStage
    */
   private GameStage stage;
   
   /*
    * this is the main root menu actor to work with
    */
   private CompositeItem menu;
   
   /*
    * this will be holding 2-ground system composite item 
    */
   private CompositeItem groundRotator;
   
   /*
    * this will be the bird sprite animation displayed in center of screen
    */
   private SpriteAnimation bird;
   
   // this variables are used to wiggle bird up and down with sin function
   private float iterator = 0;
   private float birdInitialPos;
   
   public MenuScreenScript(GameStage stage) {
      this.stage = stage;
   }

   public void init(CompositeItem menuItem) {
      menu = menuItem;
      
      // Finding playButton by id and storing in variable
      ImageItem playBtn = menuItem.getImageById("playBtn");
      
      // Finding ground composite and storing in variable 
      groundRotator = menuItem.getCompositeById("groundRotator");
      
      // Finding bird and storing in variable
      bird = menuItem.getSpriteAnimationById("bird");
      
      // let's remember where bird was initially
      birdInitialPos = bird.getY();
      
      // Adding a Click listener to playButton so we can start game when clicked
      playBtn.addListener(new ClickListener() {
         // Need to keep touch down in order for touch up to work normal (libGDX 
                                                                          awkward
                                                                          ness)
         public boolean touchDown (InputEvent event, float x, float y, int 
                                   pointer, int button) {
            return true;
         }
         public void touchUp (InputEvent event, float x, float y, int pointer, 
                              int button) {
            // when finger is up, ask stage to load the game
            stage.initGame();
         }
      });
   }
   
   /*
    * This is called every frame
    */
   public void act(float delta) {
      // moving ground left with game speed multiplied by delta as delta shows 
      what part of second was passed since last call
      groundRotator.setX(groundRotator.getX() - delta * stage.gameSpeed);     
      
      // if ground rotator got half way left, we can just put it back to 0, and 
      to eye it will look like it endlessly moves
      if(groundRotator.getX() < -groundRotator.getWidth()/2) groundRotator.setX(
         0);
      
      // Now this part is to wiggle bird up and down, we are going change 
      iterator based on time passed
      iterator += delta*400;
      
      // Then figure out the bird offset from it's original position based on 
      iterator which is based on time passed, and do it with sinus function
      float birdOffset = MathUtils.sinDeg(iterator)*5;
      
      // put bird on it's original pos + offset
      bird.setY(birdInitialPos + birdOffset); 
   }
   
}

 

BirdScript.java

 

package com.underwater.demo.overflappy;

import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.uwsoft.editor.renderer.actor.CompositeItem;
import com.uwsoft.editor.renderer.actor.SpriteAnimation;
import com.uwsoft.editor.renderer.script.IScript;

/**
 * Bird Script
 * @author azakhary
 * This is brain of the bird, it's physics and everything
 */
public class BirdScript implements IScript {

   /*
    * reference to GameStage
    */
   private GameStage stage;
   
   // Bird composite item actor
   private CompositeItem bird;
   
   // Inside bird composite actor there is the bird sprite animation actor
   private SpriteAnimation birdAnimation;
   
   // used to wiggle the bird in the air using Sine function
   private float iterator = 0;
   
   // current vertical velocity of the bird
   private float currVerticalVelocity = 0;
   
   // boolean to know if gravity is enabled or not
   private boolean isGravityEnabled = false;
   
   // to avoid jumping to rotation bird will try to always rotate a bit towards 
   desired rotation
   private float desiredRotation;
   
   // is it alive?
   private boolean isAlive = true;
   
   
   public BirdScript(GameStage stage) {
      this.stage = stage;
   }
   
   @Override
   public void init(CompositeItem item) {
      bird = item;
      
      // find animation from the composite
      birdAnimation = bird.getSpriteAnimationById("birdAnimation");
      
      // set origin of the bird in it's center, so it will rotate normally
      bird.setOrigin(bird.getWidth()/2, bird.getHeight()/2);
      
      // set desired rotation to current rotation which is 0
      desiredRotation = bird.getRotation();
   }

   @Override
   public void act(float delta) {
      
      if(!isGravityEnabled && isAlive) {
         // Wiggling when no gravity only
         iterator += delta*400;
         float birdOffset = MathUtils.sinDeg(iterator)*5;
         birdAnimation.setY(birdOffset);
      }
      
      // aplying gravity every frame
      gravity(delta);
      
      // moving to new position based on current vertical velocity
      bird.setY(bird.getY() + delta*currVerticalVelocity);
      
      // manage bird rotation based on it's vertical speed
      manageRotation(delta);
      
   }
   
   /*
    * manage bird rotation based on it's vertical speed
    * this is a part of code that is not interesting boring and whatever..
    */
   private void manageRotation(float delta) {
      if(isGravityEnabled) {
         if(currVerticalVelocity > -200) {
            float rotation = currVerticalVelocity+200;
            desiredRotation = rotation/15f;
         }
         if(currVerticalVelocity <= -200) {
            float rotation = currVerticalVelocity+200;
            if(rotation < -400) rotation = -400;
            desiredRotation = rotation/4.4f;
         }
         
         if(desiredRotation != bird.getRotation()) {
            if(desiredRotation > bird.getRotation()) {
               bird.setRotation(bird.getRotation() + 900*delta);
               if(desiredRotation < bird.getRotation()) bird.setRotation(
                  desiredRotation);
            }
            if(desiredRotation < bird.getRotation()) {
               bird.setRotation(bird.getRotation() - 900*delta);
               if(desiredRotation > bird.getRotation()) bird.setRotation(
                  desiredRotation);
            }
         }
      }
   }
   
   public void enableGravity() {
      isGravityEnabled = true;
   }
   
   public void disableGravity() {
      isGravityEnabled = false;
   }
   
   public void jump() {
      // if bird is dead do not jump (I think I checked it somewhere already)
      if(!isAlive) return;
      
      // if bird is higher then screen then do not jump
      if(bird.getY() > stage.getHeight()) return;
      
      // if jumped get the custom variable jump_speed from bird actor and set it 
      as current vertical velocity
      currVerticalVelocity = bird.getCustomVariables().getFloatVariable(
                             "jump_speed");
   }
   
   /*
    * Apply gravity each frame (get's delta time since last frame)
    */
   private void gravity(float delta) {
      if(isGravityEnabled) {
         // change curernt velocity based on gravity (gravity changes velocity 
                                                      every second by gravity 
                                                      amount)
         currVerticalVelocity -= delta*bird.getCustomVariables().
                                 getFloatVariable("gravity");
      }
   }
   
   public CompositeItem getBird() {
      return bird;
   }
   
   // get's the bird center coordinates as vector 2 needed for collision 
   detection in GameScreenScript
   public Vector2 getBirdCenter() {
      Vector2 vec = new Vector2(bird.getX() + bird.getWidth()/2, bird.getY() + 
                    bird.getHeight()/2);
      return vec;
   }
   
   // Kills the bird, for reals
   public void die() {
      currVerticalVelocity = 0;  
      isAlive = false;
      desiredRotation = 0; 
      bird.setRotation(0);
      birdAnimation.pause();
   }

}

Programming, Design , , ,

5. September 2014

 

 

Other than being a word my brain seems to think is spelled incorrectly, Particles are a common part of many games.  Fortunately Phaser has pretty good support for particles.  In this tutorial we are going to take a look at how they are used.

 

First, a quick introduction to particles.  A particle system is simply a mass of things, namely particles.  A particle is often ( as in this case ) a simple sprite.  The entire idea behind a particle system is to control a large number of particles using a single controller.  Particles are commonly used to create effects like fire and smoke, where each dozens, hundreds or thousands of smoke and flame particles are emitted ( pushed ) from the particle emitter.  As the emitter moves, so do the particles emitted from it.  This allows you to define over all behavior in the emitter, not each particle.  If that makes no sense, don’t worry, the examples below should clear it up.

 

Let’s take a look at a very basic emitter.  First we need a particle graphic.  In this case I am using the following graphic:

 

particle

 

It’s a simple transparent png image named particle.png.  Now the code:

 

/// <reference path="phaser.d.ts"/>

class SimpleGame {
    game: Phaser.Game;
    sound: Phaser.Sound;
    emitter: Phaser.Particles.Arcade.Emitter;

    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', { create: 
                    this.create, preload: this.preload});
    }
    preload() {
        // Load the image we are going to use for our particle
        this.game.load.image("particle", "particle.png");
    }
    create() {
        // Now we are creating the particle emitter, centered to the world
        this.emitter = this.game.add.emitter(this.game.world.centerX, this.game.
                       world.centerY);
        // Make the particles for the emitter to emmit.  We use the key for the 
        particle graphic we loaded earlier
        // We want 500 particles total
        this.emitter.makeParticles('particle', 1, 500, false, false);
        // And BOOM, emit all 500 particles at once with a life span of 10 
        seconds.
        this.emitter.explode(10000, 500);
    }
}

window.onload = () => {
    var game = new SimpleGame();
};

 

Now when you run this code:

 

p1

 

500 particles using our png texture “explode” out of the emitter all at once.  The code is fairly heavily commented to explain what exactly is going on so I am going to move on to the next example.

 

Some ( most? ) of the time, you arent going to want all of your particles exploding all at once, except perhaps if you are modeling an explosion that is, instead you often want them to stream over time, perhaps from a moving source.  Also, you often want to use more than a single particle graphic for variety.  Finally, you often want those particles to physically interact with the world.  This example is going to do all of this.

 

This time we are going to use multiple (poorly edited by me) image files for our particles:

particleparticle2particle3

 

And now the code:

 

/// <reference path="phaser.d.ts"/>

class SimpleGame {
    game: Phaser.Game;
    sound: Phaser.Sound;
    emitter: Phaser.Particles.Arcade.Emitter;
    sprite: Phaser.Sprite;

    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload: this.preload,
            update: this.update
        });
    }
    preload() {
        // This time we have 3 different particle graphics to use
        this.game.load.image("particle", "particle.png");
        this.game.load.image("particle2", "particle2.png");
        this.game.load.image("particle3", "particle3.png");

        this.game.load.image("logo", "gfslogo.png");
    }
    update() {
        // This checks for and handles collisions between our sprite and 
        particles from the emitter
        this.game.physics.arcade.collide(this.sprite, this.emitter);
    }
    create() {
        var start = new Date().getTime();
        for (var i = 0; i < 1e7; i++) {
            if ((new Date().getTime() - start) > 10000) {
                break;
            }
        }
        this.emitter = this.game.add.emitter(0, 0);
        // As you can see, you can pass in an array of keys to particle graphics
        this.emitter.makeParticles(['particle', 'particle2', 'particle3'], 1, 
                                   500, false, false);
        // Instead of exploding, you can also release particles as a stream
        // This one lasts 10 seconds, releases 20 particles of a total of 500
        // Which of the 3 graphics will be randomly chosen by the emitter
        this.emitter.start(false, 10000, 20, 500, true);

        // This line of code illustrates that you can move a particle emitter.  
        In this case, left to right across
        // The top of the screen.  Ignore details tweening for now if it's new, 
        we will discuss later
        this.game.add.tween(this.emitter).to({ x: this.game.width }, 10000,null,
                            true,0,1,true).start();

        // Let's create a sprite in the center of the screen
        this.sprite = this.game.add.sprite((this.game.width / 2) - 100, (this.
                      game.height / 2) - 100, "logo");
        // We want it to be part of the physics of the world to give something 
        for particles to respond to
        // Note, we will cover physics in more detail later ( after tweening 
                                                              perhaps... ;) )
        this.game.physics.enable(this.sprite);
        this.sprite.body.immovable = true;
    }
}

window.onload = () => {
    var game = new SimpleGame();
};

 

And run it:

 

p2

 

As you can see, you can provide multiple particles, move the emitter and have it physically interact with the scene.  Don’t worry over much about tweening or physics, these are two subjects we will cover later in more detail.

 

In these two examples, we’ve looked at particles like you would use for special effects work, a very common situation.  That said, Particles can actually be used to control a large number of game entities that have common over all behavior, but randomized location, rotation, size or scale.  Take for example, a flight of animated birds.  You might want to add birds flying in the background of your game.  Let’s take a look at how to do this!

 

First I am using (a full sized version) of this sprite sheet taken from here.

robin-782x1024

 

It’s an animated sequence of a robin in flight.  It contains 22 frames, each 240x314 pixels in size.

 

Now let’s take a look at the code:

 

/// <reference path="phaser.d.ts"/>


// Create our own Particle class
class MyParticle extends Phaser.Particle {
    elapsedTime: number;
    currentFrame: number;
    static MAX_FRAME: number = 22;
    game: Phaser.Game;

    // In the constructor, randomly pick a starting frame of animation so all 
    the 
    // birds arent animated at the same rate
    constructor(game: Phaser.Game, x: number, y: number, key?: any, frame?: any) 
                {
        this.currentFrame = Math.floor(Math.random() * MyParticle.MAX_FRAME);
        this.elapsedTime = 0;
        this.game = game;

        // Now call Particle's constructor, passing in the spritesheet and frame 
        to use initially
        super(game, x, y, "ss", this.currentFrame);
    }

    update() {
        super.update();

        // Ever 100ms move to the next frame of animation
        this.elapsedTime += this.game.time.elapsed;
        if (this.elapsedTime >= 100) {
            this.currentFrame++;
            if (this.currentFrame > MyParticle.MAX_FRAME) this.currentFrame = 0;
            this.frame = this.currentFrame;
            this.elapsedTime = 0;
        }
    }
}

class SimpleGame {
    game: Phaser.Game;
    sound: Phaser.Sound;
    emitter: Phaser.Particles.Arcade.Emitter;

    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload:
            this.preload, render: this.render
        });
    }
    preload() {
        // Load the spritesheet containing the frames of animation of our bird
        // The cells of animation are 240x314 and there are 22 of them
        this.game.load.spritesheet("ss", "robin.png", 240, 314, 22);
    }
    render() {
    }
    create() {
        // Now we are creating the particle emitter, centered to the world
        this.emitter = this.game.add.emitter(this.game.world.centerX, this.game.
                       world.centerY);

        this.emitter.particleClass = MyParticle;
        this.emitter.makeParticles();
        
        // In this case, we dont want gravity affecting the birds and we dont 
        want them to rotate
        this.emitter.gravity = 0;
        this.emitter.minRotation = 0;
        this.emitter.maxRotation = 0;

        // Now start emitting particles.  Total life of 1000 seconds, create one 
        per 500ms ( 2/sec )
        // and create a total of 100 birds.
        this.emitter.start(false, 100000, 500, 100, true);
    }
}

window.onload = () => {
    var game = new SimpleGame();
};

 

And when run:

 

p3

 

The terrible graphics are a side effect of being converted to an animated GIF that would take forever to download!

 

It just dawned on me that I haven’t actually covered Spritesheets yet… oops.  Hey, this is how you use a spritesheet! :)  Don’t worry if you struggle with the spritesheet portions, we will cover that later as well.  The important part here is the Particle itself.  In this example we extend the class Particle to create our own Particle class.  This class then handles updating itself resulting in the animation of the bird.  Obviously you could put a great deal more logic in there, although be sure to keep things pretty light computationally, especially if you intend to create a number of them.

 

This example actually illustrates a couple of really nice features of TypeScript, but maps nicely to Phaser’s JavaScript.  The first in the concept of a constructor.  This is code that is called as the object is created.  The next more important concept is class and extend.  In this case we are extending an existing JavaScript class, Particle.  A quick look behind the curtains now.

 

In TypeScript we write:

 

class MyParticle extends Phaser.Particle

 

This results in the JavaScript

 

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
// Create our own Particle class
var MyParticle = (function (_super) {
    __extends(MyParticle, _super);

 

Pretty cool stuff, and certainly easier to read and maintain.

 

A Small Bug

 

While writing this I ran into a small bug I figured I should make you aware of ( and one of the downsides of working with TypeScript ).  In the code sample we had the following line:

 

this.emitter.particleClass = MyParticle;

 

This line is specifying the type of class to use for a Particle, no an instance of the class.  Unfortunately the Phaser.d.ts file is incorrect in it’s definition.  It instead expects particleClass to receive a Phaser.Particle instance.  This is wrong ( and took some time to route out ).  In the definition, if not fixed by the time you read this, make the following edit to Emitter:

 

particleSendToBack: boolean;
// MJF Fix particleClass: Phaser.Sprite;
particleClass: any;

 

Hopefully that will be fixed by the time you read this.

 

Programming , , , ,

Month List

Popular Comments

Construct 3 Details Released
Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon


2. February 2017

 

Scirra just released information on their upcoming Construct 3 release and I have to imagine the response isn’t what they were hoping for.  Construct is a codeless game engine that ultimately generates HTML5 behind the scenes.  There are two major changes to Construct 3:c3

    • they have moved to a subscription model, $99 USD per year, which includes exporting to all supported platforms.
    • Construct 3 is now hosted entirely in the browser, Chrome specifically

Details from the original announcement:

Construct 3 works in Chrome on Windows, Mac, Linux, and Chrome OS. There's nothing to install — it's as simple as visiting a website. There are too many new features to list here, so we'll be posting regular updates over the next few weeks going in to more detail. However we've designed it web-first, with features like cloud save, remote preview, integrated WebFonts support, native-grade WebGL rendering, and much more. But don't worry - it'll still work fine when you go offline, even with an intermittent connection, and you can keep your projects offline too if you prefer. And as we promised, Construct 2 projects import with high fidelity. You won't have seen anything like this running in your browser before. And we're nearly ready to share what we've created.

Moving software to the web changes everything. Consequently we've had to make one change to the old way of doing things. As with the vast majority of web-based services, Construct 3 licenses will be based on a subscription rather than a one-off payment. We also know many existing Construct 2 users will be thinking about upgrading. Here's a summary of how pricing and upgrades will work.

  • A Construct 3 Personal subscription will be $99/year. This covers all export platforms.
  • Existing licensed Construct 2 users (including on Steam) will get 50% off their first year.
  • Anyone who buys Construct 2 from today until Construct 3's release will get their first year of Construct 3 for free. To make it a no-brainer, we're also putting Construct 2 on sale for $99. So there's no reason to wait!
  • If they choose, our existing Education users will be able to upgrade to Construct 3 for the remainder of their license period at no additional cost.
  • We will still have a basic free edition of Construct 3.

A public beta of Construct 3 will begin by April. At first our focus will be on testing, but we aim to make the full release by summer. We think you'll love it.

 

Judging by several of the comments in response to this announcement, the community is not exactly pleased:

image

image

image

 

It’s not all negative though, there were a few positive comments in the mix:

image

 

One major point of contention is the browser based nature and the requirement to be online, to which the Construct team responded:

image

 

I personally don’t mind browser based tools, but I do dislike single browser based tools.  With every release I am liking Chrome less and less and being tied to a single browser eliminates a lot of the web based advantage to start with.  Want to work in Safari on your iPad… you can’t.  Most recent Chrome update broke on your computer…  good luck with that.

 

Today, Scirra followed up with another blog post actually previewing upcoming changes in Construct 3.  (Personally I would have lead with this….)

The interface

The Construct 3 interface has been redesigned from the ground up. We've kept many familiar and useful aspects, like the panes layout and the Properties Bar. There are also some significant differences. We've aimed for a simplified, minimal design that reduces clutter and helps you focus on your content. The ribbon has been condensed down to a toolbar with just the most essential features. Everything else is now under the main menu button.

Being browser-based, the UI style can be modified using CSS. We're keen to add a custom theming system to allow anyone to edit the appearance!

Log in to Construct 3

Near the top-right corner is the user account menu. In this screenshot it's showing a guest user who hasn't logged in. You'll be able to log in to Construct 3 with the same account you use on the website. This makes it dead easy to use Construct 3 on any computer, at home, work or school. Remember, there's nothing to install! We can't wait for you to try this.

High-quality display

This screenshot was taken on a 4K high-DPI display. The high-DPI rendering in Construct 3 is flawless: every detail scales perfectly. The icons for example are all SVG, which means they scale perfectly to any size or detail. The icons have also all been redesigned with a modern flat style like Google's material design. The Layout View also works perfectly with high-DPI displays, and also features zoom-to-mouse, a greater zoom range, and native-equivalent rendering with WebGL 2. Also note the lack of a status bar - instead status appears when it is needed, and in the right context, such as inside the Layout View pane.

Improved properties

The Properties Bar has also been reworked to be easier to use with extra conveniences. For example you can click the "..." button by the project description to edit the text in a larger window. Checkboxes are used instead of on/off dropdowns. You can type calculations like 1920/2 which will set a value of 960. You can even use some system expressions like sqrt(64). Number values can be dragged smoothly with the mouse and instantly show the effect in the Layout View.

Fully-featured

You might be wondering how we handle features that have previously required external software like Java for the minifier, or PNGCrush for image recompression. We didn't want to settle for fewer features in the browser, so we created a suite of equivalents, several of which are compiled to asm.js for near-native performance. Then we went a step further and created a scheduling architecture that uses Web Workers run tasks in parallel across all available CPU cores for maximum performance. This all ensures you can do everything in the browser - not just a subset or "lite" version, it's the real deal.

Can I work offline?

We want to be absolutely clear on this - Construct 3 will work offline! We're using the latest Service Worker technology to download the entire app the first time you visit it. Every time you visit after that, it will load directly from disk. So you can be offline, or have an intermittent connection, and you won't even notice - Construct 3 will keep working. We recognise forcing users to be online would be a significant inconvenience for many users, so we've worked hard to make the sure the offline or "lie-fi" experience is perfectly smooth.

You can of course also keep your projects offline if you prefer. We think many people will find it convenient to save and load from the cloud, especially if you use several different devices. However this is not required - you can still save and load projects locally, as you can with Construct 2.

In future we are also planning desktop builds of Construct 3 for Windows, Mac and Linux. These will work much like Construct 2 does now: you download and install the software, can copy it to a USB drive, and so on. These versions will also cover the surprisingly small featureset that can't be covered in the browser, such as saving a folder-based project to a local folder, and better copy-and-paste support. This allows you to take Construct 3 to a computer that is permanently offline, for example.

 

So, what do you think of the changes to Construct 3.  As was illustrated recently with Unity, many people find subscriptions completely abhorrent.   I also know many people strongly dislike browser based tools as well.  This combination is a bold choice, but one that is sure to alienate a portion of their user base.  The question remains is… how much?

GameDev News

blog comments powered by Disqus

Month List

Popular Comments