Explore Free Game Engine Tutorials – GameDev Academy https://gamedevacademy.org Tutorials on Game Development, Unity, Phaser and HTML5 Wed, 19 Apr 2023 05:30:47 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 https://gamedevacademy.org/wp-content/uploads/2015/09/cropped-GDA_logofinal_2015-h70-32x32.png Explore Free Game Engine Tutorials – GameDev Academy https://gamedevacademy.org 32 32 Kaboom.js Tutorials – Complete Guide for Easy Game Dev https://gamedevacademy.org/kaboom-js-tutorials/ Sat, 21 Jan 2023 05:11:59 +0000 https://gamedevacademy.org/?p=14977 Read more]]> Do you want an easy-to-use game framework to build your dream projects?

Kaboom.js is a relative newcomer to the game development scene, but it is already making a big splash – especially among indie creators. This JavaScript-based library was made specifically with games in mind, in the same vein of frameworks such as Phaser or Pixi.js. However, there are many aspects that have made it stand above its competitors and worth your time checking out.

In this article, we’re going to introduce you to Kaboom.js and show you how you can get started learning this new tool.

Let’s get started!

What is Kaboom.js?

As mentioned, Kaboom.js is a JavaScript library in the vein of HTML5 games, which use the browser to render games made with it. The library was made with the idea of simplicity, but comes with many important game development features – such as layering, collision detection, input handling, and more. Regardless, though, the goal is to allow novice developers to create game scenes as quickly as possible.

Game objects in Kaboom.js are conveniently rendered with a component-based system. This means they’re extremely easy to manipulate and apply behaviors too. The behaviors can include everything from simple game mechanics like health to basic movement-based animations – so each game object essentially suits object oriented programming principles.

Beyond this, it is worth noting Kaboom.js is also an available template for Replit – a popular, in-browser coding environment. This means its well-suited for developers who aren’t interested in setting up local development environments or just want to play around with the library.

Key Pros of Kaboom.js

Why should you use Kaboom.js? Below, we’re going to explore what makes Kaboom.js stand out and how, as a developer, you can benefit from the advantages Kaboom.js offers.

Screenshot of the Kaboom.js playground

Fast and lightweight

Unfortunately, not everyone has a computer that can run game engines such as Unity or Unreal Engine – which both are pretty process intensive programs. However, Kaboom.js does not require a great computer and can be used even with low-end laptops. In fact, due to its incorporation with Replit, as mentioned above, you really only need a browser if you’re intent on using it – not even a code editor is required.

Likewise, because of how lightweight it is, games made with Kaboom.js run very smoothly as well. This means you don’t have to get hung up too much on optimization. Instead, your games will likely run quickly right out of the box, leaving you more time to focus on what matters.

No dependencies

Many frameworks and libraries out there require several layers of dependencies to be able to run properly. If you forget the dependency, or more tragically, if the dependency has a breaking change, your game isn’t going to work.

Kaboom.js doesn’t require any sort of dependencies. While you certainly can add packages such as webpack, natively you just need to import the Kaboom.js library itself. Once that is added, you won’t have the extra worry of maintaining the dependencies. This helps Kaboom.js achieve its goal of making it quick to setup and allowing you to dive straight into the fun stuff of actually making the game.

Cross-platform compatible

Since Kaboom.js is specifically for creating browser-based games, this means that there are no platform limitations. If the device can connect to the internet, your players can play it from anywhere.

For you as a developer, this means two things. First, this helps you avoid messy setups of needing multiple game versions just to have it available for multiple platforms. Second, this opens you up for a wider audience since you can tap into different sorts of players. All in all, though, this is a boon that makes it much easier for you to get the game into multiple different hands.

Simplicity

If you’ve ever tried to read documentation for frameworks or libraries before, you’ll know they can get rather complicated. If you don’t believe us, just go check out Unity’s documentation. While certainly this is fine for experienced developers, beginner developers are going to find this a nightmare.

Kaboom.js was designed to eliminate this problem and be as simple as possible. Not only does this help with keeping it lightweight, but makes the documentation much, much easier to understand when you’re just a beginner. This, in turn, just makes development itself easier.

Additionally, it comes with the extra benefit that this documentation can more easily be maintained as the library is updated. This means you won’t be reading old information that was relevant five versions ago.

Specifically made for beginners

As you might have seen from the previous points, beginners were at the heart of the design choices for Kaboom.js. Everything about the library is made to benefit beginners who have never made a game before. While there is a need for JavaScript experience before diving in, this is a much lower point of entry compared to heftier engines.

Thus, you’re only going to need a few tutorials to get the gist of how Kaboom.js works – and soon be able to develop your own projects with it.

Active development

Over the years, many HTML5 frameworks have come and gone. For others that remain, the development can often be slow and new versions, bug fixes, and features are few and far between. While many of these frameworks still technically work, the lack of developer support can eventually become a hindrance.

Kaboom.js, on the other hand, is very actively and caringly developed. Though we don’t expect them to break their principles of simplicity, improvements to the library come frequently. Thus, you can be assured the library will be supported for whatever time it needs for you to build your project.

Screenshot of the Kaboom.js GitHub page

What can you make with Kaboom.js?

Being based on HTML5 (i.e. for the browser), projects made with Kaboom.js do have limitations – as our browsers and internet are only so powerful no matter which JS library we’re talking about. So, you shouldn’t expect to make any kind of AAA game with the library. Kaboom.js was also specifically made for 2D development, so 3D graphics are kind of off the menu as well.

Past these two minor limitations, though, Kaboom.js does not put any further obstacles in your way. You can build small games in just about every genre, and only your imagination is there to hold you back. This includes everything from platformers to adventure games to old-style retro games like Breakout, Super Mario Bros.Space Invaders, and so forth.

If you want to explore the full scope of what people have already made, you can check out Kaboom.js made games below:

Kaboom.js & JavaScript Tutorials

Ready to create games with Kaboom.js? Check out the links of tutorials below which cover Kaboom.js, JavaScript for HTML5 development, and the game development process.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
Generative AI in Game Development – Complete Guide https://gamedevacademy.org/generative-ai-in-game-development-complete-guide/ Fri, 20 Jan 2023 00:11:35 +0000 https://gamedevacademy.org/?p=19940 Read more]]> What is generative AI?

Generative Artificial Intelligence (AI) uses machine learning algorithms in order to create content. This content can take multiple forms such as images, 3D models, audio, text, animations and more. Generate AI took the world by storm in 2022 with popular applications such as ChatGPT, Stable Diffusion, Dall-E and Mid Journey.

Stable Diffusion Examples

Stable diffusion examples from the official repository

The advent of generative AI has unleashed a new wave of creation and change that is already impacting all aspects of our lives. This includes, of course, the process of game making.

How does generative AI work?

In non-technical terms, what these models do is essentially mathematical operations in huge matrices of data. These models are called neural networks (for an example of the simplest possible neural network, the Perceptron, see this tutorial).

In order to use a generative AI model, that network needs to be trained. Training is the fine-tuning of the model’s parameters so that it can give us the results we are after. The training of these models requires huge amounts of data – in some cases, pretty much the entire internet.

Tiny robot at a computer

This is actually not AI-generated. It’s a stock image we paid to be able to use a while back.

The largest models such as those created by OpenAI cost millions of dollars to train, however that cost has been steadily coming down, with the open source Stable Diffusion model costing “only” $600,000  to train.

The fact that the whole internet is the training set for these models can explain why they are able to generate assets not only in the majority of art styles known to humankind, but that they are also able to create work that is “in the style of” niche artists (some of which are, understandably, not happy about it).

What game assets can we create with generative AI?

At this point in time, some of the main applications that have been made available to the broad public are the generation of 2D images, text and computer code.

Nvidia AI screenshot

There are, however various other applications in the horizon that are currently being showcased by large tech companies such as Google and NVIDIA, AI researchers, startups and hobbyists. These include textured 3D models, animations, video and audio (voice and music).

What’s the vision with generative AI in games?

This is, of course, pure speculation. In a non-distant future, it is likely that we’ll be able to generate entire games based on a prompt. For example, we might be able to write “create a platformer game taking place in Santiago, with a horror theme and packed with people-eating potatoes, pixel art, medium difficulty, with retro music”, and obtain a playable demo of such a game, with assets, a storyline, and source code.

Dragon AI Generated with Stable Diffusion

Prompt “low-poly rainbow dragon”

Not only will we be able to create new games with AI, but those games will be able to adapt and respond to the players in ways that were unthinkable today, to the point where they could be totally different to each player based on their gameplay and preferences.

Also, generative AI has the potential to bring the cost down for what today is only possible with +100M budgets and huge teams. This would be a huge leveling in the playing field in the industry, but not without many other consequences that we’ll talk about later.

What is a more immediate application of generative AI?

An immediate application of generative AI is in the creation of game content. That is, an AI might be able to create new levels, characters, dialogs, music, quests, within an existing game.

It’s important to mention that a lot of this is already possible using procedural generation and other techniques. With all the buzz around generative AI, the fact that a lot of this is already possible has been somewhat forgotten, so it is common these days to see articles mentioning this as if it was the first time that it was possible.

A Guide to Procedurally Generated 2D Maps

Using procedural generation, we are already able to create not only levels but entire galaxies (see No Man’s Sky and other games in the genre), as well as textures, animations, storylines and much more.

So what is generative AI able to add here? Well, quite a few things. From the developer’s perspective, procedural generation level, while certainly a lot of fun and easy to get started with (see our Procedural Generation course), does become complex as you scale the number of variables and aspects in your game.

The procedural generation of other game content like textures and audio can be highly complex from a mathematical standpoint. It is much easier and quicker for iteration to tell an AI “undulating sand”, than it is to implement and finetune a terrain generation code.

While procedural generation can do a lot, it is more time-consuming and complex, and therefore, expensive, than using AI prompts, that’s not where the advantages of AI end. With generative AI we can also pull from a much larger catalog of resources and can provide our games with infinite more variety. There are, certainly risks to it as we’ll cover in a bit.

Another benefit of this technology, in particular for game development enthusiasts who don’t have a design/art background. I believe that those developers will really benefit from generative AI.

I’ve personally stopped working on personal projects once I had to look for textures and 3D models, as you end up in an Asset Store-induced choice paralysis kicks in. With generative AI, it is quick to get some decent-looking graphics into your personal projects and continue making progress.

Will generative AI render game developers and designers obsolete?

Only a few years back, people were saying that no-code tools were going to render developers and designers obsolete. All of the sudden, anyone could create websites with the likes of Wix, games with GameMaker or apps with App Inventor.

What ended up happening though was not what had been predicted. As no-code tools made it easier for people to create prototypes, that did indeed reduce the need for developers/designers in a super early stage. But when the cost of production was reduced, the cost of user acquisition increased. If you have 10x more apps wanting people’s attention, that is bound to create a more competitive landscape.

Zapier No Code Example

What tends to occur next is that in order to win this race, your app, game or product needs to differentiate, which by definition, cannot be easily copied, and again, that pretty much implies that you’ll need to push those no-code tools to the limit in which they break (meaning, you either need actual code, or the no-code project is large enough to require software engineering best-practices, or it needs a human design element that the tool itself cannot provide), and voila! you need developers/designers to take it from there.

I’m providing this example from the entrepreneur’s perspective, but think of this same dynamic taking place across companies of all sizes that are competing for customers. Winning customers attention and wallets is often a zero-sum game. That tends to create a complexity arms race that will push players out of the comfort of the no-code tools and pre-made designs.

Where am I going with this? When generative AI becomes pervasive, and everyone can generate a AAA title with a prompt, why would I want to play the game that such and such generated, when it’s not gonna be better than what my “no code” AI tool can do? We’ll the way to make a game more interesting will be to add developer/design value on top of what the AI can create, in order to make it different and more distinct.

So in summary, yes, I expect that they (we, I should say) will still be needed, provided we all learn to add value on top of what generative AI tools can offer.

What are the main risks when using generative AI in your game?

The largest risk by far is that of copyright. Firstly, a disclaimer. I’m not a lawyer and none of this is legal advise. Copyright is generative AI’s elephant in the room. As somebody with no conflicts of interests here, I can appreciate both sides of the argument.

An artist not being compensated for the use of their work is not fair or appropriate in modern society, especially when their works are driving billions in revenue. There are already lawsuits taking place.

Prompt “trial against an ai inside a court of justice, with a magistrate and robot witnesses, 4k photo realistic style”

On the other hand, the pro-generative AI argument is that human creativity is built on what others have created in the past, including “training” our brains with other people’s work. There is unlikely to be a single professional artist on Earth who has never seen (and therefore, registered in their neurons) another person’s work. What generative AI has done is turn this existing process into an algorithm.

The courts and society will need to agree on a framework for AI training that takes everyone’s interests into account. I suspect this will be ironed out one lawsuit at at time.

In saying that, should be careful when using generative AI. If you generate a “Mickey Mouse surfing” image, is that yours or Disney’s? While I don’t know the answer to that, it is not something I’d dare to put into question. It is easy to avoid using works that you are familiar with, there could be copyrighted content in your AI-generate images without you knowing it.

What I would recommend is to do an Image search of the assets that you generate with AI, if you are looking to use them commercially. Again, none of this is legal advice, and empty Image Search results are no guarantee of the absence of copyright.

Regardless, generative AI is here to stay. The open source code is already in the wild, and people can always choose to train an AI with their own work, or with work that is already in the public domain.

What’s the main usability issue with generative AI?

Customization, customization, customization. This is where I’ve struggled the most in my own forays into the different tools.

It’s easy to write prompts and create say an elf character in vector art, but it is not that straightforward to then take that exact elf and generate different poses or reuse those characters in other prompts, or to remove the background for a clean sprite sheet.

Prompt “elf warrior character in vector art for videogame”

There is a lot of work being done on these fronts, but it is still not easy or quick to do. I’ve noticed a similar thing when it comes to the art style and color palette. In the future, I’d like to see the ability to set a design tone, color palette, etc, and that the AI or the software built around it is able to distinguish the different entities and characters (example ability to generate a character, and then to have a “jumping animation” for that same character).

In terms of easiness of use. I’ve seen several startups build web-based tools to create game assets, including Scenario and Mirage. They are all doing an amazing work in the space in terms of improving the experience for game developers and designers. I’m super excited in seeing how this new ecosystem of products takes off.

As a personal take for usability, the way I would actually like to use this is inside my preferred game engine. When Probuilder was added to Unity, I ditched Blender for most simple things. I find it easier to keep my workflow in the Unity editor itself. Likewise, with generative AI tools, I’d like to be able to generate this assets directly within the game editor, the photo editor or the 3D modeling tool, and not to have to use more services. This might be a very opinionated view, but regardless, the minute Unity and the other engines have some of this in-built, most people will be too lazy to use other websites unless they really have to.

]]>
KaiOS Game Development Tutorials – Complete Guide https://gamedevacademy.org/kaios-game-development-tutorials/ Wed, 18 Jan 2023 10:20:49 +0000 https://gamedevacademy.org/?p=14202 Read more]]> Although many of us enjoy our hardy Android and iOS smartphones with regular consumption, there is no doubt that this is not the case for everyone. Some regions simply do not have access to common smartphones in a regular capacity. For others, most smartphones are simply just too expensive. Then there are consumers who just don’t like the data plan stipulations that come with regular Android and iOS smartphones. Regardless of the reason, these mobile operating systems and phones are just not for everyone, and that can be a problem for mobile developers.

However, did you know there was an alternative that not only overcomes these issues, but opens up a new audience for aspiring developers to aim for? In this post, we’re going to introduce you to KaiOS, and help you find the KaiOS game development tutorials you’ll need to start creating for this new platform!

What is KaiOS?

To put it plainly, KaiOS is an alternative mobile operating system for phones initially released in 2017. The entire operating system was based off of an open-source project which aimed to continue the work of the old Firefox OS that was abandoned by Mozilla. With KaiOS, the main aim of this alternative operating system is to help increase internet access and phone availability for users who have not yet been able to access these modern conveniences.

According to KaiOS, the expensive price of phones and touchscreen learning curves are a big factor in why billions of people still aren’t accessing the internet. With the KaiOS, though, companies who volunteer can easily get a license for the operating system and develop hardware for it. As the operating system was built to be extremely lightweight, this has allowed companies to put the KaiOS on keypad feature phones, which in turn are able to be sold for a much, much cheaper price than the average Android or iOS phone. Nevertheless, these phones are still able to come with modern technology like 4G, Wi-Fi, and GPS, giving a whole new set of people access to mobile devices.

In addition, apps for KaiOS still are able to offer plenty of robust experiences, as everything is based on HTML5. Thus, the operating system offers cross-platform compatibility for developers wishing to create software for KaiOS devices.

Advantages of KaiOS?

Why would someone want to develop for KaiOS, though – especially compared to something like Android and iOS? There are some very distinct advantages this newfound operating system can offer for keen developers who want to try it out!

HTML5 Based

As mentioned earlier, apps for KaiOS are web-based on HTML5. As such, there are only three things you really need to know to start building them: HTML, CSS, and JavaScript. This makes the development process not only very easy to learn, but multi-functional as these are the same pillars for the entire web development sector too. Even further, this means it’s very easy to make cross-platform applications, so even if you don’t get any bites from KaiOS, you still have other markets like Android and iOS that can access your projects.

No Touchscreen Considerations

While it’s not impossible for KaiOS to someday aim for touchscreen devices, one of the main advantages is that KaiOS can be put on old-style keypad phones. Thus, when developing games or apps, you don’t really need to worry about whether or not the user tapped, dragged, or anything else that involves touch-based controls. This can take off a lot of pressure when developing – especially if this is your first journey into mobile devices.

Access to New Regions

Due to its affordability and the company’s own aim, KaiOS is able to get into regions where Android and iOS devices aren’t necessarily as prevalent or popular. This includes places like India, Africa, South America, and even many parts of Asia. As such, there is a huge audience, some of whom have never even accessed the internet before KaiOS, just waiting to play your games or use your apps.

Quickly Growing Platform

Although KaiOS is new, the platform is already growing quickly. In fact, according to Android Authority, KaiOS is already the second most popular OS for phones in India, beating out iOS. Even places like the US are seeing a number of users switch over to KaiOS simply due to the cheaper price point. To match this, many different companies, such as Google, Atari, Mozilla, AT&T, Sprint, T-Mobile, TED, and beyond, have partnered with the KaiOS company. As such, it’s not unwise to say the platform is growing in both audience and support, so it’s not going anywhere anytime soon and is quite stable for new-time developers.

Uncrowded Market

Earlier we mentioned that KaiOS only came out in 2017. While some might interpret this as a bad thing, since the market isn’t as established as the other mobile operating systems, this can also be a good thing. For anyone who has developed for Android or iOS, you know both their respective stores have, well, a lot of apps and a lot of competition. As KaiOS is a lot newer, though, the market is a lot less crowded. Because of this, there is an opportunity for developers who jump in early to establish their games and apps before any other competitor, thus giving them more opportunities for success.

Screenshot of the KaiOS app store

What Can You Make for KaiOS?

While KaiOS still comes with generalized mobile device limitations (i.e. you aren’t gonna make Dark Souls), there are plenty of opportunities for different styles of mobile apps and mobile games. This includes:

  • Apps for Entertainment
  • Productivity apps
  • Utility apps (weather, clocks, etc.)
  • Common Webapps like Facebook, WhatsApp, and so forth
  • HTML5 games in any genre

… and more! We highly recommend checking out KaiOS most popular apps from 2020 for a better idea, or simply browse the KaiOS app store to see the kinds of apps are possible.

Tutorials

You can dive into KaiOS game development & app devel9opment by checking out the tutorials below and taking advantage of this new platform for your projects!

About KaiOS

User Tutorials

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
Roblox Game Making Tutorials – Complete Guide https://gamedevacademy.org/roblox-game-making-tutorials/ Sat, 14 Jan 2023 08:19:57 +0000 https://gamedevacademy.org/?p=13831 Read more]]> Roblox is an online game platform that has been very popular since its release in 2006, and is largely driven by its enthusiastic community. There are thousands of custom-made games that are open for the public to play in a multiplayer setting, ranging from simulations to battle royales.

As well as being able to play games, though, you can also create your own with Roblox’s versatile game engine known as Roblox Studio. Roblox game making is not only fun for all ages, but allows you to easily create pretty much anything that comes to mind – and multiplayer support is built-in already. With its vibrant community and many opportunities, jumping into Roblox game making has never been easier.

BUILD YOUR OWN GAMES

Get 250+ coding courses for

$1

AVAILABLE FOR A LIMITED TIME ONLY

Roblox Studio Features

Roblox Studio offers a ton of features to help you in the Roblox game making process including:

  • A large online library of 3D models, textures, images, etc.
  • Use of the Lua programming language to script game logic.
  • Well-documented API information.
  • The ability to instantly publish games online which are immediately ready to be played with friends.

roblox studio editor

Who is this For?

Well, if you want to create a multiplayer game to play with friends and don’t want to tinker around with networking code and servers – then Roblox Studio is for you. It’s also a great introduction into game development as it strips away all the daunting complexity of other engines.

If you already have experience in other game engines such as Unity, Godot, or Unreal – then Roblox should have a fairly easy onboarding process as well. The structure of the engine is similar to those mentioned, and learning Lua should be easy if you already have experience in C#, C++, GDScript, etc.

Another benefit of Roblox is that the whole experience of creating and playing games is self-contained. You don’t need to host servers, manage distribution platforms, etc. You hit the publish button and your game is out there for potentially millions of people to play. Roblox also facilitates monetization, so if your game becomes popular you could earn some money. So if you are just starting out with game development, or just want less complicated multiplayer development – then definitely give Roblox Studio a go!

Popular Roblox Games

There are millions of different games for you to play on Roblox. Here’s a few of the most popular ones.

Here’s the trailer for Arsenal. A multiplayer FPS game in Roblox.

How to Start with Roblox Studio

Alright, so you want to make Roblox games – how do you begin? Well, let’s start by downloading the game engine here. Click on the Start Creating button and you can download the software.

roblox create page

Once you’ve logged into Roblox Studio, you should have the program open. Go to the New page and double-click the Baseplate template.

roblox studio template page

The engine should then open up.

roblox studio editor

The only thing we have in our game right now is a baseplate (floor) and a spawn location (this is where the players spawn). To move things around, you can click on them to select (you should see a blue outline). Then you can hold down the left mouse button and drag around to move the part.

Now as you create your games, you’ll want to test them out. At the top of the window, you’ll see a row of different tabs. Click on the TEST tab and click on the Play button.

roblox studio test tab play button

You’re now playing the game! But there’s not much to do here. When you want to stop playing the game and get back to creating, click on the Stop button.

roblox studio stop playing the game

Ok, so you’ve got the game engine open and you know how to play the game. But how about adding in some content? An obstacle course? Combat? Below is a list of tutorials to get you started!

Roblox Tutorials

Lua Tutorials

Lua is the programming language we use to script our Roblox games. These tutorials will help you out if you’re totally new to coding.

Roblox Community Links

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
What is Game Design? A Guide for Making Video Games https://gamedevacademy.org/what-is-game-design/ Fri, 13 Jan 2023 06:10:04 +0000 https://gamedevacademy.org/?p=13301 Read more]]> It is no real secret that making video games is a complex and intense process – whether you’re creating a simple platformer or something as robust as an MMORPG. This complexity begins first and foremost at the idea stage where the life essence of all video game projects begins. As much as some people might wish it, though, simply thinking of an idea doesn’t make a video game come into existence.

So, what is an aspiring video game maker supposed to do once they have the idea? This is where the story of game design begins, a fascinating subfield of game development that is crucial to the entire process.

In this article, we’ll explore what game design even is at the very foundation, how game design exists as a career, and help you understand why it is so critical to the world of game development at large. We’ll also provide you with a ton of resources so you can learn the “how” of game design too and apply it to your projects!

BUILD YOUR OWN GAMES

Get 250+ coding courses for

$1

AVAILABLE FOR A LIMITED TIME ONLY

Defining Game Design

In this first section, we’re going to take a look, first and foremost, at what game design is at the most base of levels. This will not only establish a good foundation as we explore how video game design functions as a career, but also help out beginners coming in not quite sure how to define it!

Two women planning out the UI for a mobile application

What Game Design is

Game design can be considered the planning arm of the entire process for making a video game. No video game gets made without a plan, and video game design is, more or less, the process of making that plan. The field is somewhat a hybridization of creativity and technical skills that combine into a cohesive, fleshed-out idea that people can work with using concrete and actionable tasks.

However, that is a lot to unpack, so let’s break everything down a bit more in layman’s terms.

Creative Side

As mentioned, all video games start with an idea. This idea can simply be something like:

  • “I want to make a platformer where the princess is the player character.”
  • “I will make a choice-based story RPG set in a Lovecraftian-inspired world.”
  • “I think it’d be cool if there was a one-hit kill battle royale video game.”

What the idea is doesn’t particularly matter, but the point is that these are the sparks that kickstart the game design. From there, though, this idea is not enough yet to make a video game. Instead, we’re left with a lot of questions:

  • What does the princess player character look like?
  • How are “choices” presented in the video game – dialogue or implemented in the gameplay itself?
  • How can a one-hit kill video game be balanced for fun rather than frustration – and is it multiplayer or singleplayer?
  • What sorts of weapons and/or items are available in these video games?
  • Do these video games have some deeper story?

We can certainly go on and on with these questions, yet what you may not realize is answering these questions is a large part of what game design is about! These are the exact elements that help you design the game – from the characters and plot, to the design of the levels, to the mechanics of how the video game is played, to the expression of the mechanics in a way that is fun, and even to aesthetics. Every little aspect like this must be answered, and game designers are the ones to do just that.

In essence, they take that base idea, and create a narrative out of it – just a specific one that helps elaborate on what elements need to be decided on and made piece by piece to make the whole puzzle of a video game come together.

Woman drawing technical things in the air

Technical Side

However, as creative as this might all sound, we can’t neglect to elaborate on why video game design is also still a technical field.

On the one hand, most game designers are actually expected to know a bit of programming, computer science, and math. While in bigger teams they might not be expected to program at all, they do need to have the background knowledge to oversee the game’s production. After all, if a programmer on the team makes something that doesn’t test well, the game designer is going to have a hard time communicating the technical problem unless they are familiar with the game’s construction.

So, having the necessary technical background will, at the very least, make communication easier as you polish and finetune the game design.

This is not to mention that many different game genres require pretty intense math and balancing. For example, if you’re making a city-building strategy game, you need to be able to plan costs, plan resources, plan timetables for construction or resource gains, and so forth. This will need to be tested, rebalanced, tested again, rebalanced again, and so forth. In order to do these tasks, as well as make the initial formulas, a strong understanding of math is needed.

Beyond this, game design can also be a lot about some of the humdrum business aspects as well, including things like planning the game around the target audience.

For example, according to GameRefinery, while realism is the preferred graphic style in the west for mobile games, Japan prefers anime-styled art across the board for their video games. So, depending on which market you were targetting, the art style choices of the game design might change drastically given that. While definitely not the most creative, these still are important factors to consider during the planning process.

Summary

Overall, game design is one part creativity with deciding the atmosphere, story, and aesthetics of the video game, and one part technical know-how deciding game mechanics, balancing, and so forth. Game design is a robust field of study that involves just as much knowing how and why to do a certain thing as it is using your imagination to create novel possibilities.

However, no matter which side you talk about, game design is about creating the initial plan, knowing the tools and techniques to create that plan, and how that will dictate how the full game comes together as one experience. This is a concept that surpasses many other aspects of video game development, such as even what game engines to use.

Bar chart and facts regarding the popularity of art styles in various world regions

Differences from Game Developer

Before we move on to talking about game designers as a professional career, let’s stop for a moment to talk about the elephant in the room. In other words, how does a game designer differ from a game developer?

This is a tricky question, as it depends on each game designer’s personal situation, some nuanced technicalities, and the exact context in which each term is used. However, we can try to break it down as best we can.

First and foremost, most game designers can be considered game developers. Rather than being entirely separate, game design can be considered a subfield of the entire video game development process. Generally, even for something like a UX/UI designer for a game, these subfields still encompass people considered to be game developers at the heart of the issue. Certainly, they have specialties, but they’re still part of the development team.

That being said, when most people are using the term “game developer”, they are generally speaking not of the specific subfields, but of the general programmers who work with the designer and plan out the super technical aspects like data structures, objects, and so forth. It’s also assumed these developers have a good grasp of computer science in comparison to other specialties.

We go more into depth on the entire field of game developer in this article, but the important point here is the context of how the terms are used generally refer to different things entirely – one about planning and one about programming.

Then again, it is worth pointing out that in the indie sector, where many video games are solo developed, the game designer can also be the sole “game developer” in charge of everything. As such, there is some huge crossover in activities. No game is made without a plan, so someone at some point has to do the game design.

All in all, though, the best way to navigate the world is to focus on game design as a specific subfield rather than focus on the differences. At the end, everyone involved in making a game is an important member of the game development process.

Computer with hands typing code onto the screen

Game Design as a Career

Now that we understand what game design is, let’s dive into the actual practice of it as a career in the gaming industry. Even if you’re only interested in video games as a hobby, this still may be a worthwhile section to explore just to get an understanding of a game designer’s everyday life – as game design is not all fun and playing games. It may also give you some insight into what awaits you should you make that critical decision to start this career path.

Activities

To begin, we’ll start by talking about the sorts of activities a professional game designer might do in the gaming industry as a whole. With your new understanding of game design, many of these will be no surprise.

However, before proceeding, let’s establish one thing: every game designer, video game, and game development studio is different. Some activities on this list a video game designer may never touch depending on the makeup of the team and what the video game is (as different types of video games need different things), whereas others might do all of them and then some. So, be sure to consider this when deciding if this is the right career for you or not!

  • Script/story writing: If a story is involved with the game, a game designer might spend a lot of time working on those aspects. This includes establishing the setting and history, establishing characters and their backstories, planning out the narrative plot, and potentially writing all the dialogue that will be used throughout the game. In larger teams, the game designer may simply coordinate with dedicated writers to get some or all of these various aspects done. Nevertheless, a game designer will often be intimately involved in getting the story off the ground.
  • Planning and creating game art: Part of a game designer’s duties is to decide the game’s aesthetics. This can include creating basic character designs, environment visual designs, and so forth. Technical decisions will also be made here, such as whether to do pixel-art, 3D graphics, etc. Now in some cases, a game designer will make a basic concept, which they then turn over to a professional game artist to flesh out into a usable piece for relay to asset creators. In other cases, the game designer’s own art may serve as the final concept art from which the game assets are made.
  • Designing levels/puzzles/challenges: One thing almost all video games have in common is that there are “levels” – i.e. spaces where the game is played. Even if a single-level game – for example, a fighting game stage – every block, aesthetic, and critical path will be planned out by the game designer. This can also include planning out battle encounters, puzzles, and similar should the specific game call for that. Besides planning, a game designer may also be one of the main members implementing the levels into the game by placing assets and so forth – allowing them to tweak things as they go to create the best game possible.

Screenshot of a puzzle platformer made with Unity

  • Planning interfaces: If there is no dedicated UI/UX designer on the team, guess what falls to the game designer? Whether an inventory screen, some sort of video game encyclopedia, health and hunger bars, or even simply a text score, all these interfaces need to be planned to exist, placed strategically, and have their aesthetic design decided on. Game designers will spend a huge amount of time designing this aspect, as it is one of the main ways players interact and receive information from a video game.
  • Developing gameplay: As mentioned earlier, one of the main things video game designers do, even more so than the activities above, is decide on the exact mechanics of the game and how it is played. Even if it’s just how fast a player character jumps, a game designer will serve a critical role in deciding these aspects. This process usually begins with a game designer writing a Game Design Document so everything is laid out, whether for just them or for a larger team. From there, a game designer will tweak the design further so every minute detail presents well and feels good as a player plays through the game.
  • Collaboration and communication: Depending on team size, another activity video game designers might do in the professional world has to do with both collaboration and communication. In the previous activities, we discussed how in some cases, a video game designer may delegate certain tasks to specific specialists. When that is the case, a game designer will spend a lot of time communicating and collaborating with those team members to make sure everything created – whether that be art or the programming itself – fits the specifications of the design. GitHub is a tool that makes collaboration easily, as it allows you to communicate with your team and implement version control.
  • Programming: Once again, this activity depends entirely on the situation. However, many game designers do participate at least somewhat in the programming activities of the video game. This can range from very literally doing it themselves, to simply helping out other programmers and overseeing certain technical aspects so it is a match for what the designer intended. At the very least, some programming knowledge is helpful even if you don’t do it, since some aspects of game design are reliant on the technical limitations.
  • Testing and changing: Finally, and a big one for video game designers, is testing and changing the video game they’re working on. Besides being fun, video games at their heart are supposed to have a consistent, quality experience. Game designers will spend a long time testing every aspect of the video game to test how it feels to play, whether there are any mechanics that are broken or ruin the competitive nature of the video game, and so forth. Once those issues are discovered, they help tweak the game design until the final video game product is the very best it can be as far as the core design goes.

Woman playing a computer game

Job Outlook & Salary

While job availability will always vary depending on location and experience, game design can be a lucrative career to get into. According to Career Explorer, the United States alone has nearly 300,000 positions for game design. Their sources estimate that this will grow from 2016 to 2026 by 9.3%. Other sources, such as DegreeQuery which gathers information from the United States Bureau of Labor Statistics, put the job growth anywhere from 4% to 10% depending on specific data used.

These sources also indicate that game designers who specialize in mobile games will often have more ample job opportunities going forward.

On the salary front, even junior designers can expect to earn quite a bit. Without considering specializations, the job sites below reported the following salary ranges for game designers in the US:

Salaries might also vary greatly by company. For example, PayScale shows Bungie having the lowest salary for game designers at $61K, while Age of Learning, Inc. and Electronic Arts both pay over $85K for their game designers. Experience can also play a big role, with developers seeing an average of $10,000 more per year for every 1-5 years more experience they possess.

As you can see, though, game design is both in-demand and a profitable field to pursue. Further, game design can be even more profitable as you specialize, especially for things like UI/UX design.

List of average salaries for game developers

Becoming a Video Game Designer

By this point, not only should you have a good idea about what game design is, but also maybe you want to become one now – whether that means joining a professional AAA company or simply solo-developing some video games as a hobby. Whatever your ultimate goals, though, we’ve compiled some of our tips and resources to help you take the first steps on this amazing journey and master game design!

Get the Technical Skills

We’ve long since established that game design is not just about having creative ideas – it’s also about technical skills and knowing how and why to do certain game design things (not to mention knowledge of computer science).

So, obviously, the first step here is to get some technical skills and master the basics, both of game design and its many facets, and of programming. We’ve broken some helpful tutorials and online courses below to get you started on your journey.

Voxel tree made with MagicaVoxel

Programming

General Game Design

Game Art

Game Writing

Charts of various aspects of game design

Make a Video Game

Once you have the basics down, the next step in the journey to becoming a game designer would be to simply put it in practice and make your own games (in any of the popular game engines).

This not only allows you to practice your skills, but also lets you build a portfolio which is crucial if you’re trying to get hired. Plus, as we’ve established above, game design is an expansive field that is about game mechanics, UIs, and more. So the more opportunities you put each aspect of game design into practice, the more you’ll find what works from you.

Below we’ve compiled some of our favorite resources that will help you make your first video game. Keep in mind, we’ve also included some non-computer games in this list as well, since game design principles (like good mechanics) are still as relevant to board games, card games, and so forth. Also, don’t forget to expand past these tutorials as well – game design is about experimentation!

Text-based RPG example made with C++

Conclusion

By this point, we hope you have a good idea of what game design is. Game design is an essential component to all games no matter how large or how small. Without game design, projects would fall through quickly. With a concrete plan, though, any developer can bring a project into reality.

Additionally, game design is recognized as an important position in larger companies, with high salaries and a need for the in-demand skillsets involved. It is not just thinking of ideas, but understanding how to logically and systematically arrange those ideas in a way that produces a fun game.

All this being said, we’ve only just scratched the surface here. There are a lot of skills involved with game design – from understanding how to guide players, to understanding high-level concepts like game loops. However, with the resources provided, you can definitely dive deep into the field and even join the video game industry. Maybe you’ll even make the next hit game. 😉

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
Create a Basic Multiplayer Game in Phaser 3 with Socket.io – Part 1 https://gamedevacademy.org/create-a-basic-multiplayer-game-in-phaser-3-with-socket-io-part-1/ Mon, 19 Dec 2022 12:57:07 +0000 https://gamedevacademy.org/?p=6753 Read more]]> In this multipart tutorial, we will be using Phaser 3 and Socket.io to create a simple multiplayer game. For our multiplayer game, we will follow the client-server game architecture. If you are not familiar with the client-server game architecture, the client is responsible for displaying the game to the player, handling the player’s input, and for communicating with the server. The server, on the other hand, is responsible for broadcasting that data to each client.

The goal of this tutorial is to teach you the basics of creating a multiplayer game. You will learn how to:

  • Setup a Node.js and Express server that will render our game and communicate with it.
  • Setup a basic Phaser 3 game that will act as our client.
  • Use Socket.io to allow the server and the client to communicate.

Course Files and Versions

You can download all of the files associated with the source code for part one here.

At the time this tutorial was written, the following versions were used. You may need to use these versions to have the same results from this tutorial.

  • Node.js: 10.13.0
  • JSDOM: 13.0.0
  • Express: 4.16.4
  • Socket.IO: 2.1.1
  • Datauri: 1.1.0

BUILD YOUR OWN GAMES

Get 250+ coding courses for

$1

AVAILABLE FOR A LIMITED TIME ONLY

Tutorial Requirements

For this tutorial, we will be using Node.js and Express to create our server. We will also be using NPM to install the required packages we need for the server to run. In order to follow along with this tutorial, you will need to have Node.js and NPM installed locally, or you will need access to an environment that already has them installed. We will also be using the Command Prompt (Windows) / Terminal (Mac) to install the required packages, and to start/stop our Node server.

Having a prior experience with these tools is a plus, but it is not required for this tutorial. We will not be covering how to install these tools as the focus of this tutorial is making a game with Phaser. The last thing you will need is an IDE or Text Editor for editing your code.

To install Node.js, click the link here: and choose the LTS version. You can download and use the current version with this tutorial, however, the LTS version is recommended for most users. When you install Node.js, NPM will also be installed on your computer. Once you have these tools installed, you can move on to the next part.

As a last note, we do not recommend this tutorial be used by educators looking for new classroom resources. Instead, try Zenva Schools which features K12-friendly courses on web development and game development – plus classroom management features.

Setting up the server

The first thing we are going to do is create a basic Node.js server that will serve our game files. To get started, create a new folder on your computer, it can be called anything you want. Then navigate inside this folder and create a new file called server.js. Open up server.js and add the following code to it:

var express = require('express');
var app = express();
var server = require('http').Server(app);

app.use(express.static(__dirname + '/public'));

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});

server.listen(8081, function () {
  console.log(`Listening on ${server.address().port}`);
});

In the code above we:

  • referenced the express module, which is a web framework that will help us render our static files.
  • created a new instance of express and called it app.
  • supplied the app to the HTTP server, which will allow express to handle the HTTP requests.
  • updated the server to render our static files using express.static built-in middleware function in Express.
  • told the server to serve the index.html file as the root page.
  • had the server start listening on port 8081.

Before we can run the server, we will need to install the required modules for the server. Open your terminal/command prompt, and navigate to your project folder. Once there you will need to run the following command: npm init -f. This will create a package.json file in your project folder. We will use this file to keep track of all the packages that our project depends on.

Now, we will install express. In your terminal run the following command: npm install –save express. This will create a folder called node_modules in your project folder, and by adding the –save flag to the command, npm will save this package in our package.json file.

Setting up the client

With the basic server code finished, we will now work on setting up our client-side code. In your project folder, create a new folder called public. Any file we put in this folder will be rendered by the server that we set up. So we will want to put all of our static client-side files in this folder. Now inside the public folder, create a new file called index.html. Open up index.html and add the following code to it:

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
    </head>

    <body>
        <script src="//cdn.jsdelivr.net/npm/phaser@3.0.0/dist/phaser.min.js"></script>
        <script src="js/game.js"></script>
    </body>

</html>

In the code above, we set up a simple HTML page and we referenced two JavaScript files, phaser.min.js (the phaser game framework) and game.js (our Phaser game code). Back in the public folder, create a new folder called js , and in this folder create a new file called game.js. Open up game.js and add the following code to it:

var config = {
  type: Phaser.AUTO,
  parent: 'phaser-example',
  width: 800,
  height: 600,
  physics: {
    default: 'arcade',
    arcade: {
      debug: false,
      gravity: { y: 0 }
    }
  },
  scene: {
    preload: preload,
    create: create,
    update: update
  } 
};

var game = new Phaser.Game(config);

function preload() {}

function create() {}

function update() {}

Let’s review the code we just added:

  • We created the configuration that will be used for our Phaser game.
  • In the config object, in the type field, we set the renderer type for our game. The two main types are Canvas and WebGL. WebGL is a faster renderer and has better performance, but not all browsers support it. By choosing AUTO for the type, Phaser will use WebGL if it is available, otherwise, it will use Canvas.
  • In the config object, the parent field is used to tell Phaser to render our game in an existing <canvas>  element with that id if it exists. If it does not exists, then Phaser will create a <canvas>  element for us.
  • In the config object, we specify the width and height of the viewable area of our game.
  • In the config object, we enabled the arcade physics that is available in Phaser, and we set the gravity to 0.
  • In the config object, we embedded a scene object which will use the preload, update, and create functions we defined.
  • Lastly, we passed our config object to Phaser when we created the new game instance.

With our basic client-side code setup, we will now test our server and make sure everything is working correctly. Back in the terminal/command prompt, run the following command: node server.js and you should see the following line appear Listening on 8081. Now, if you open up your web browser and navigate to http://localhost:8081/, you should see a black box on the web page, and if you open the console in the developer tools, you should see a log with the version of Phaser your game is running.

Blank Phaser 3 game running in Google Chrome

Adding Socket.IO

With our server now rendering our game, we will now work on adding Socket.IO to our game. If you are not familiar with Socket.IO, it is a JavaScript library that enables real-time, bi-directional communication between web clients and servers. To use Socket.IO, we need to update our client and server code to enable the communication between the two.

Back in your terminal, run the following command: npm install –save socket.io. If your server is still running, you can either: open a new terminal window and run the code in your project folder, or stop the server (CTRL + C) and then run the command. This will install the Socket.IO node package and save it in our package.json file.

Now, in server.js add the following code below the var server = require(‘http’).Server(app); line:

var io = require('socket.io').listen(server);

Then add the following code above the server.listen line:

io.on('connection', function (socket) {
  console.log('a user connected');
  socket.on('disconnect', function () {
    console.log('user disconnected');
  });
});

In the code above we:

  • referenced the socket.io module and had it listen to our server object.
  • added logic to listen for connections and disconnections.

Next, we will update the client side code to include the Socket.IO library. Open up index.html and add the following line at the top of the <body> element:

<script src="/socket.io/socket.io.js"></script>

Then, open up game.js and add the following line inside the create function:

this.socket = io();

Now, if you start the server back up again, and refresh your game in your browser, you should see the user connected/disconnected messages in your terminal.

Console information denoting users connecting and disconnecting

Adding players – Server

Now that we have our socket connections setup, we can move on to adding players to our game. In order to keep all of the player’s games in sync, we will need to notify all players when a user connects or disconnects from the game. Also, when a new player connects we will need a way to let the player know of all the other players in the game. To do all of this we will need to store some player data, and we will use the socket connections to send messages to our players.

For this tutorial, we will store the player data in memory on the server. Normally, we would want to store this data in some type of database, that way it would be persistent, and if the server fails, we could easily recover the state of the game.

In server.js add the following line below the io variable:

var players = {};

We will use this object to keep track of all the players that are currently in the game. Next, in the callback function of the socket.io connection event add the following code below the console.log(‘a user connected’); line:

// create a new player and add it to our players object
players[socket.id] = {
  rotation: 0,
  x: Math.floor(Math.random() * 700) + 50,
  y: Math.floor(Math.random() * 500) + 50,
  playerId: socket.id,
  team: (Math.floor(Math.random() * 2) == 0) ? 'red' : 'blue'
};
// send the players object to the new player
socket.emit('currentPlayers', players);
// update all other players of the new player
socket.broadcast.emit('newPlayer', players[socket.id]);

Let’s review the code we just added:

  • When a player connects to the web socket, we store some player data in the players object and we use the socket.id as the key.
  • We are storing the rotation, x, and y position of the player, and we will use this to control were we create sprites on the client side, and use this data to update all players games. We also store the playerId so we can reference it in the game, and we added a team attribute that will be used later.
  • We used socket.emit and socket.broadcast.emit to emit an event to the client side socket. socket.emit will only emit the event to this particular socket (the new player that just connected).  socket.broadcast.emit will send the event to all other sockets (the existing players).
  • In the currentPlayers event, we are passing the players object to the new player. This data will be used to populate all of the player sprites in the new player’s game.
  • In the newPlayer event, we are the passing the new player’s data to all other players, that way the new sprite can be added to their game.

When a player disconnects, we need to remove that player’s data from our players object, and we need to emit a message to all other players about this user leaving, that way we can remove that player’s sprite from the game.

In the callback function of the socket.io disconnect event add the following code below the console.log(‘user disconnected’); line:

// remove this player from our players object
delete players[socket.id];
// emit a message to all players to remove this player
io.emit('disconnect', socket.id);

Your server.js file should look like the following:

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);

var players = {};

app.use(express.static(__dirname + '/public'));

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
  console.log('a user connected');
  // create a new player and add it to our players object
  players[socket.id] = {
    rotation: 0,
    x: Math.floor(Math.random() * 700) + 50,
    y: Math.floor(Math.random() * 500) + 50,
    playerId: socket.id,
    team: (Math.floor(Math.random() * 2) == 0) ? 'red' : 'blue'
  };
  // send the players object to the new player
  socket.emit('currentPlayers', players);
  // update all other players of the new player
  socket.broadcast.emit('newPlayer', players[socket.id]);

  // when a player disconnects, remove them from our players object
  socket.on('disconnect', function () {
    console.log('user disconnected');
    // remove this player from our players object
    delete players[socket.id];
    // emit a message to all players to remove this player
    io.emit('disconnect', socket.id);
  });
});

server.listen(8081, function () {
  console.log(`Listening on ${server.address().port}`);
});

Conclusion

With our server code for adding players in place, this brings part one of this tutorial to an end. In part two we wrap up our multiplayer game by:

  • Adding the client side logic for adding players to our game.
  • Adding logic for player input.
  • Adding collectibles for the players to collect.

I hoped you enjoyed part one of this tutorial and found it helpful.

Note that if you feel a bit out of debt, don’t be afraid to explore some basic web development courses first for individuals or even for teachers to use in the classroom.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
The Complete Guide to Scratch and Coding for Beginners https://gamedevacademy.org/scratch-tutorial/ Mon, 19 Dec 2022 09:37:07 +0000 https://gamedevacademy.org/?p=19299 Read more]]> Are you or someone you know a first-time coder?

If you’ve never coded before, finding the right place to start can be difficult. However, no matter the age, a good first tool/language to explore is Scratch.

Scratch is a visual coding language that allows for the creation of digital stories, games, and animations by anyone who’s interested – including kids. Scratch is also the world’s largest coding community for children and is available for free in more than 70 different languages.

In this tutorial, you’ll learn the basics of coding through the implementation of a mini-project that animates the movement of a cat sprite in Scratch.

If you’re ready to dig in, let’s get started!

Projects Files

The code for our final cat animation can be downloaded here: Cat Animation in Scratch. Although we will guide you along every step of the way, it’s good to also have the complete code so that you can compare it to your version at any time!

We also recommend you check out our Jr Coder Mini-Degree (for learners) or Zenva Schools (for teachers) to explore more topics pertaining to coding with Scratch.

BUILD YOUR OWN GAMES

Get 250+ coding courses for

$1

AVAILABLE FOR A LIMITED TIME ONLY

A Closer Look at Scratch’s Interface

To start this tutorial off, we’ll first explore how to create Scratch projects and explore the interface!

Creating a new Project

First off, head over to the Scratch homepage then click on ‘Create‘:

Scratch homepage interface

This will initiate a new project as seen below:

New project in Scratch

Game Stage

At the top-right corner, we have the game stage where we can see our animation running:

Game stage in Scratch

We can click on the green flag icon above the game stage to start our animation and on the red button to terminate it. Note that as we don’t have any code to run just yet, it only shows its default cat sprite for the moment. By clicking on the rightmost icon above the game stage, you can also put it in fullscreen mode:

Fullscreen mode in Scratch

Sprite Properties

To alter the cat’s position inside the game stage area, just drag it around as you wish. You’ll see that its x and y coordinates in the sprite properties panel vary according to its current location:

Sprite properties panel in Scratch

Here in the properties, we can also rename the sprite to ‘Cat’ and change its size and direction too. To hide or display your sprite, click on the eye icons next to ‘Show’.

At the bottom of the right-hand side of the screen, the sprite area shows us all the sprites we have in our project (only the cat, in our case). To add more sprites, click on the plus button:

Adding a sprite in Scratch

From there, you’ll have a huge variety of options to choose from. When you add a new sprite to the project, it will appear next to the previous ones you already had:

Multiple sprites in Scratch

To delete a sprite, just click on the trash bin icon that’s on top of its thumbnail:

Deleting a sprite in Scratch

Changing the Background

Next to the sprites, there’s the backdrop area, where you can select a different background for your animation:

Changing the background in Scratch

Changing our default white background to ‘Room 2‘ (under the ‘Indoors‘ filter), we’d have:

'Room 2' background in Scratch

Block Palette

On the left side of our screen, on the other hand, we have all possible blocks of code that we’ll be using in our code. Each block contains a single instruction for the computer to execute and is assigned to one of the various categories shown below:

Block palette in Scratch

Workspace

And finally, to the very center of the screen is the workspace, where we’ll be placing all our code blocks:

Workspace in Scratch

Making our First Code

Now that we’ve grasped the Scratch tool, it’s time to move on to the main part of making a Scratch project: block-based coding.

To start our project, let’s delete the cat sprite and add a chick character (or feel free to add the sprite of your choice):

A chick sprite in Scratch

In Scratch, we build our program using blocks that we can select from the block palette on the left side of the screen. Let’s begin by clicking and dragging the first block from the Motion category (the one that says “move 10 steps“) to the workspace:

Adding a code block to the workspace in Scratch

Now, every time you click on this block the chick sprite moves 10 steps in the game stage. You can check its new position by the updates on its x coordinate in the sprite properties panel.

Note that you can also change the number of steps the chick will move each time by entering a new number directly in the block itself:

Altering the code inside the block in Scratch

Although we already have a line of code, when we click on the green flag to start the program nothing happens. This is so because we need to add a starting event in order for our character to move when the green flag is clicked. To do it, go to the blocks under the Events category:

Adding events to the code in Scratch

Then, drag the “when green flag clicked” block to the workspace and place it on top of the move block that is already there:

Adding 'when green flag is clicked' event in Scratch

With this, whenever we click on the green flag our character moves 10 steps to its right.

Adding More Blocks

On the blocks palette, go to Looks and drag the “say Hello! for 2 seconds” block to the workspace, connecting it under the move block as follows:

Making the sprite say Hello! in Scratch

Note that the blocks fit together perfectly. We can change both text and duration if we want:

Altering contents of the block command in Scratch

Clicking on the green flag, we see it is working correctly:

Running our code in Scratch

Go on and add the “think Hmm… for 2 seconds” block to our code as well:

Adding more Looks blocks to our code in Scratch

Order of Execution

It’s important to notice how all these commands are always executed in order, from top to bottom:

Order of execution of the commands in Scratch

First, we are moving the sprite 10 steps, then we make it say ‘Hi’, and at last we make it think ‘Hmm’.

If we were to place the think block before the say one, we’d see that the character would think ‘Hmm’ first and only then would say ‘Hi’:

Inverting the order of two blocks in the code in Scratch

Remember that if you want to stop the program at any time, you need only press the red icon next to the green flag.

Adding Sounds

Let’s add a sound to our program. Bring the “play sound until done” block from the Sound category to the workspace:

Adding Sound blocks in Scratch

The suggested sound ‘Chirp’ is matching the sprite we’ve chosen, so it may differ for you.

At last, let’s move the chick again by 20 steps:

Our first program complete in Scratch

Play the animation one more time to see the whole execution take place.

One Script for Each Sprite

Bear in mind that our code is only being applied to the chick sprite. If you add a new sprite, the workspace will appear blank for that sprite while our code remains there normally for the chick:

Different sprites have different codes associated to them in Scratch

And just like that, our first computer interactive program is done, and it already responds to user input by moving our character on the stage!

Algorithms and Flowcharts

We’ve covered a lot of ground in how the block-based coding of Scratch works. However, you might be asking, “Why” and “How” we knew what blocks to use. For that, let’s take a step back and discuss one of the most fundamental aspects of coding.

What is an Algorithm?

You may not realize it, but you have just created and executed an algorithm! Algorithms are everywhere and are not only related to computer science stuff. An algorithm is merely a sequence of steps that solves a real-world problem. In this sense, coding or programming is simply the process of making algorithms for a computer to execute.

An example of an algorithm from our daily lives can be something as common as making a piece of toast. It could be represented by the following steps:

  1. Put a slice of bread into the toaster
  2. Set the toasting level
  3. Lower the lever
  4. Wait until the toast is ready
  5. Safely remove the bread from the toaster

As you can see, an algorithm lists all of the steps that are needed in order to achieve the desired outcome. In other others, an algorithm is nothing but a set of instructions that need to be followed in a specific order!

Flowcharts

Algorithms can be visually described by a flowchart. Our toast example above would produce this flowchart here:

Flowchart on how to make a toast

We specify the start of our algorithm with a ‘Begin‘ block (in blue) then proceed to place statement blocks (green rectangles), each containing one of the steps of our algorithm. We finish it by adding an ‘End‘ block (also in blue) to point out where the algorithm ends. Note that although we’re using specific colors in this tutorial, they are not part of the flowchart convention. Flowcharts don’t need to have any particular colors.

Flowcharts are useful for code documentation and to allow us to check that we’ve implemented everything correctly, and have not skipped any of the necessary steps of our algorithm. With all this in mind, let’s now create a brand new project so we can move on to making our first animation in Scratch!

Using Coordinates

You may have noticed in the above section, we also mentioned the “x coordinate”. Before we proceed to our final first project, let’s talk about this concept so you understand why it’s important to moving sprites.

We’re going to use coordinates to move and position our sprite on the screen. For every spot on the game stage, we have a corresponding value for x and y that form the coordinate for that particular point in the grid. Coordinate (0, 0), also known as origin, is right at the very center of the game stage:

Cat sprite located at origin in Scratch

To help us better visualize how coordinates work, let’s choose a new background. Click on the ‘Choose a Backdrop’ button and search for “coordinates“, then select ‘Xy-grid‘:

'Xy-grid' background in Scratch

This background allows us to see the values of x and y for the entire stage area:

X and y axes in Scratch

The X-axis values increase as we move to the right and decrease to the left, so if you move left past zero you’ll have negative values for x. Similarly, values of y increase as we move the sprite up and decrease as we bring it down the game stage past the X-axis.

You can also enter specific values for one axis or both axes and the cat will be repositioned automatically:

Updating the sprite's coordinates in Scratch

Cat Animation Project

Now that we have a good understanding of Scratch, we’ll put everything to the test by making a Scratch animation involving simple sprite movement.

Before we step into the actual code for our new project, let’s rename it to ‘Cat Animation’ at the top bar:

Renaming our project in Scratch

For this project, let’s change the background once more to ‘Bedroom 2‘:

'Bedroom 2' background in Scratch

We’re choosing a new backdrop because we want to make our cat sprite move to the drawer, later to the computer desk, then to the window, and lastly to the bottom right corner of the carpet of the bedroom.

For our animation to start when the player clicks on the green flag button, let’s initiate our code by adding the event block for when the green flag is clicked:

'when green flag clicked' event in Scratch

As we want to have our cat positioned by the bed once the animation is started, we can use the “go to” block (from the Motion category):

'go to' block in Scratch

To know which values for x and y to enter, we can place the cat where we want it to be at the start of our animation (in this case, on top of the bed) and then use the same coordinates shown in the sprite properties panel in the motion block in question. That is so because if you manually move the sprite around in the stage and then proceed to use any block that has the sprite’s coordinates, the block will already have the sprite’s updated location on it. Also, note that each category has a color, so, when you see a block you can automatically identify from which category that block is.

Now if we click the green flag icon, the cat is moved to the bed straight away:

Sprite moved to bed in Scratch

Next, we want to move the cat to the drawers next to the bed. Here, we’re going to use the “glide” block instead:

Using a 'glide' block in Scratch

The glide block takes the amount of time indicated in seconds to move the sprite, thus it’s not immediate as the go to block.

Challenge

Now that we’ve shown you the basic process, try the rest yourself first! Update the coordinates and complete the remaining steps:

  1. Glide the cat to the computer
  2. Glide the cat to the window
  3. Glide the cat onto the carpet

All moves should take 2 seconds each. Don’t worry if you get stuck – we’ll cover the final code next.

Challenge to move the cat to target locations in Scratch

Final Code

The solution to the challenge is as follows.

Let’s add another glide block to our code, and move the cat to the computer:

Moving the sprite to the desk in Scratch

Note that we’ve changed the duration of our first glide block to 2 seconds as well just so it matches the following glide blocks we’ll have.

Repeat this process for the window and carpet:

Final code for our cat animation in Scratch

Our code is now complete! Running the code we see that everything goes as expected:

Running our code in Scratch

In the end, the cat is standing on the carpet by the bottom right corner of the bedroom.

If you have solved the challenge in a different manner, that’s fine! Quite often there is more than one way to do the same thing in programming. In case you couldn’t solve it, don’t worry as you can always keep practicing now that you’ve seen how the challenge was solved!

You can run our cat animation project by heading over to the public project page at https://scratch.mit.edu/projects/667377329/

Cat Animation Flowchart

Finally, let’s check the flowchart for our animation project:

Flowchart of our cat animation Scratch project

For this flowchart, we’re using a new type of block (the one in orange) which can be used for user input/output, such as waiting for the user to press a button (as is the case above) or displaying a message to the user.

Conclusion

Congratulations on reaching the end of this tutorial! By now you not only have coded your first program in Scratch, but have also already created your first animation! You also have learned about algorithms and how to create flowcharts to better visualize the steps being taken.

Coding is an important skill that can be developed at any age and is being included more and more in schools in general. It improves creativity & problem-solving, and can offer a wide range of careers worldwide for those who take it professionally. Likewise, Scratch is used throughout the globe across many different age groups. With its intuitive drag-and-drop interface, it’s easy to learn the basics of programming and practice coding by trying out the various types of blocks from all the available categories in the block palette.

If you want to build more interactive projects in Scratch, you can check out the Jr Coder Mini-Degree offered by Zenva. This curriculum covers a slew of different Scratch projects and programming principles to help expand your skills and give you a solid understanding of programming in general.

On the flip side, for teachers who want to use Scratch as a tool for their classroom, Zenva Schools can help you out. Zenva Schools is an online platform that offers coding courses for use in the classroom on a variety of subjects, including Scratch, Python, HTML & CSS, and Unity. With other features such as pre-mapped course plans and reporting, it can be a fast and easy way to introduce students to a myriad of important digital topics.

In any case, we hope that you continue to explore and create real-world programs and games – and most of all that you have fun while doing it!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
Drawing Sprites with SFML & C++ – Game Dev Tutorial https://gamedevacademy.org/sfml-cpp-sprites-tutorial/ Mon, 19 Dec 2022 01:00:27 +0000 https://gamedevacademy.org/?p=12495 Read more]]>

You can access the full course here: Discover SFML for C++ Game Development

Want more coding topics for a school environment? The Zenva Schools platform which offers online courses, classroom management tools, reporting, pre-made course plans, and more for teachers.

Drawing Sprites

We’ve seen how to draw a basic shape but realistically, most of our games will use more than shapes. We will want to place graphics, icons, and other images into our games and we do so via Sprites. Setting up a Sprite is generally done in two steps with SFML: first, we load in a texture, then we create a sprite and pass in the texture. Once we have the sprite set up, we can set attributes such as the size and position and then display it by drawing it into the window during the run loop.

In our project, we should create a folder called assets that contains any assets needed in our game. We only have 4 so there’s no need to further divide the assets folder. Copy the “enemy.png” and “background.png” images, the “damage.ogg” audio file, and the “Arial.ttf” font files from your provided files and paste them into the assets folder. We will only work with the Enemy.png image for now. To create a texture, we first create a texture variable and then call the loadFromFile() function, passing in the path to the file as a string. It returns true if successful and false otherwise so we should perform a boolean test to see if the load was successful. In our main function, write this code after the code to create the window and before the run loop:

sf::Texture texture;
if (!texture.loadFromFile("assets/enemy.png")) {
  std::cout << "Could not load enemy texture" << std::endl;
  return 0;
}

This will create a variable of type sf::Texture and load the image into it. If the load fails, we print an error message and return. Sometimes, the load for an asset fails for some unknown reason so we should handle any errors properly. You will need to #include <iostream> at the top of main.cpp as well. Once we have the texture, we can create a sprite object called enemySprite and pass in the texture like this:

sf::Sprite enemySprite;
enemySprite.setTexture(texture);

The sprite will only be as big as the image provided and will default to be at position (0,0) or in the upper left corner. We can change the position like this:

enemySprite.setPosition(sf::Vector2f(100,100));

Which brings the sprite 100 pixels out from the left and 100 pixels out from the right and increase the size of the sprite by scaling it like this:

enemySprite.scale(sf::Vector2f(1,1.5));

This will scale the width of the sprite by 1 (no change) and scale the height to 1.5x its original height. Notice how both functions take an sf::Vector2f as inputs and each needs an x and y value. In order to draw the sprite, we change the draw code to this:

window.clear();
window.draw(enemySprite);
window.display();

We always have to clear the window before drawing anything and display the window after we draw to it.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

Transcript

What’s up everyone? Welcome to our tutorial on Drawing Sprites. Here we’ll get a quick intro into what sprites are from a game context and how to create and use them in SFML.

So this is actually a two step process, the first thing we need to do is create a texture object. Once we have that we can create a sprite from it and then we can set the position and the scale. So let’s head to the code and get started. Alright, so just a quick heads up again, I took all the code from the previous section, not that we really did very much and put it in old code and I’ll continue to do this with each new section.

Alright, so what is a sprite from a game context? Well essentially, a sprite is gonna be an object in the game that has an image associated with it. So this is really the main difference between let’s say shapes and sprites in games is that a sprite has an image and a shape just has well a shape. It just has its boundaries, it has some sort of code to dictate what shape those boundaries will take on, be of circles, square, rectangle, etc.

So in our case, the background of our game and the enemy itself, those are both going to be sprites, we’re not really gonna be working with shapes very much. So like I said this is a two step process. The first thing we need to do is load in a texture and a texture needs an image to load. So that’s why I had you load in your assets folder. So your project should look like this, sfml project, you have your codes, and then you have your assets folder with the items in it. We’ll use the ttf as a font later on. Same with the damage.ogg, that’s for sound. For now we’ll at least want the enemy.png because that’s what we’re gonna be working with here. Okay, so as long as we have it in our project assets /enemy.png, then we can load it in like this.

Okay, first thing that we’ll need to do is create a texture itself so we’ll do sf, Texture, texture. Okay, now a texture just like the Render Window is part of the SFML Graphics library. Anytime you need a new module, you’ll need to load it in here. Okay, so we have a texture object, we actually don’t need to call a constructor, set it equal to a texture or anything like that. Once we create the object, we have access to it immediately and we need to call the load from file function, like this texture.load From file, oops! Not load from stream we want load from file.

Okay, and then we’re going to pass in the path to the file. So in this case this is gonna be “assets/ “enemy “.png”. Now this is actually gonna return true or false based on the success or failure. So we’re gonna say something like if text actually, we’ll say if not texture.load from file, then maybe we’ll just print out some message and return. So let’s just close that off and this should actually be in here.

Okay, so in this case, what we can do is something like Standard c out, I actually don’t think we have the iOS stream library so I’m just gonna include that now. Include your stream. Okay, good stuff. Okay, so now what we’ll do is c out something like “Could not load, “enemy texture”. Okay, and then we’re just going to end it.

All right and because we really want the game to only run if the texture is loaded, we’re actually gonna return false. Cool, so as long as this is the case oh actually you know what? This is returning will turn zero. Okay, so as long as the texture is loaded, so as long as this doesn’t return zero, then we have a texture rather an image loaded into this texture, and now we can use it with a Sprite. So to do that, we’ll do basically the same process as with the texture, we need to create the sprite object first, Sprite and we’ll call this like enemySprites or something.

Okay, and then we’re going to call upon the enemySprite . setTexture function and then we’re I’m just going to pass in the texture that we loaded. Okay, so this will associate a texture with a Sprite. So now the sprite is created It has a texture and we can draw it. We don’t know exactly what size or position well we do know what position it will be in which will be 00 by default which will be upper left corner and the size will be exactly the size of the image itself. We can modify that later on, and which we’ll do in just a minute here.

Okay, so just using the default values, if we want to draw this to the window, we simply call upon the window.draw and then pass in the Sprite. So in this case, enemySprite. Okay, cool. So we’ll get this Save, and let’s run the code, let’s see what happens. So clear it, let’s compile it, and then let’s run it and now you can see that we have this little sprite in our game.

Obviously there are some issues here it’s getting cut off so the screen is not big enough to begin with. Also, this is kind of in the top left corner, we might not want it there and might not be quite big enough. Okay, so this is all stuff that we can just maybe let’s do a 500 by 500 window. That way we have enough size to draw most of the things that we need. Then if we go to rerun it, we should probably see that’s not gonna take up the whole screen anymore. It’s just take up a part of it. So maybe we don’t want it in the top left. Maybe we want it kind of a bit centered.

So what we can do is maybe move it about 100 pixels to the right and 100 pixels down, might put it roughly in the center, okay. So what we can do is take this enemy sprite, enemySprite, okay and we can set the position of it. So, this is gonna take in an a Vector two f object like this SF Vector two f which will take in a vector two dimensional float, and this will need a width and a height or an X and Y value. So in this case, we’ll just do a 100 and 100. Okay, if we go to lets close this off, we go to rerun it.

Okay, so recompile it, again, every time you make a change, you have to recompile it, you can see that this has now moved, we can also change the height, let’s kind of make this guy a little bit taller, but we won’t necessarily change the width of it. So what we can do is lets close that up do the enemySprite . And we can scale it. Okay, weirdly enough, you can’t assign a specific width and height, you actually have to scale things.

Okay, so in this case, we’re going to again pass in a vector2f, capital V, Vector two f, okay and then we’re going to pass in the amount by which we want to scale the x and the amount by which we want to scale the y. So the x is going to remain exactly the same. So we’ll just do one, the y however, we want to change the height, maybe we’ll do like a 1.5 and see how that works out.

Okay, so we’ll go back to here. Well, I guess we don’t need to clear it. We’ll just kind of recompile and we’ll rerun it and now you can see that this guy is horribly stretched, but at least the scaling worked. Now there are plenty of other things that we can do with Sprites but this will be pretty much the extent of what we’re gonna do in this course with our Sprites.

One last thing to note before moving on to the next section is that the sprites bounding box is actually this whole rectangle. Weirdly enough, the bounding box doesn’t follow the image like this. This is gonna be the bounding box. So when when it comes to detecting mouse clicks on the sky, even if you click up here, it’s technically within the bounding box. So that’s going to register a click. Okay, we’ll get more into that a little bit later on. Just wanted to make you guys aware now. Okay, we’ll close this up.

Otherwise, that’s it. So in this section, we covered two things, loading in textures, and the second creating sprites and assessing their attributes. Definitely Feel free to play around with this. Maybe try to load in your background. See how well you can do with that. When you’re ready to move on, we’ll do pretty much the same thing but with text. So stay tuned for that. Thanks for watching and see you guys in the next one

Interested in continuing? Check out the full Discover SFML for C++ Game Development course, which is part of our C++ Programming Bundle.

For teachers, you can also try Zenva Schools which offers online learning suitable for K12 school environments and offers a wide array of topics including Python, web development, Unity, and more.

]]>
An Introduction to Animating with Scratch https://gamedevacademy.org/scratch-animation-tutorial/ Tue, 09 Aug 2022 10:28:21 +0000 https://gamedevacademy.org/?p=16480 Read more]]> Coding is one of the most important skills that you can learn to improve your creativity and logical thinking – hence preparing you for a wide range of careers worldwide. However, coding doesn’t have to be all numbers and boredom, and instead, you can do something fun with it: animate.

With this tutorial, you’ll learn the basics of animating with code using Scratch by building a fish animation. While some familiarity with Scratch will help, this tutorial is perfect for any age since it doesn’t require much knowledge!

If you’re ready to learn how to make coding fun, let’s dive in.

What is Scratch?

Scratch is a free visual coding tool developed by the Massachusetts Institute of Technology (MIT) for creating games and interactive media. As it uses code blocks instead of text-based coding, it’s very easy for even kids to use as they practice basic computer algorithms.

If this is your first time using Scratch, head over to the Scratch homepage and create a new project (or use one you already have if you wish). Although we’re not going over how to switch sprites or add a background, it all is pretty intuitive to get done.

Projects Files

All the contents of this tutorial can be downloaded here

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

Animating a Fish Sprite

For this tutorial, we have a fish sprite on an underwater backdrop in Scratch – and we want our fish sprite to move every time we press the green flag above the game stage:

Green Flag on Top of Game Stage in Scratch

First, drag the ‘when green flag clicked‘ block from the ‘Events‘ category to the workspace:

Adding 'when green flag is clicked' Block to the Code

By having this block in our code, we’re saying that everything that comes below it is going to be executed whenever the green flag is clicked.

Adding Bubbles Sound

Next, we can add a bubble sound to our sprite. Over the ‘Sound‘ category, bring the ‘start sound‘ block to your code and pin it under the block we have already there:

Changing the Sound to 'Bubbles'

Click on the arrow to replace the ‘ocean waves’ sound with ‘bubbles‘. If you press the green flag now, you’ll hear the bubbles sound already.

Moving the Fish Around

To move the fish, we use the ‘Motion‘ block that says ‘glide 1 secs to random position‘:

Adding Glide Block to the Code

Glide takes the sprite to a new position over a period of time. That is, it’s going to move the fish to any position within the background area where the entire movement will only take 1 second. If you click on the green flag, you’ll see it moving:

Moving the Fish Sprite

Note that you can alter the duration (numbers of seconds) the movement is taking by typing a new value on top of the current one.

Repeating the Animation

At the moment, our fish sprite is moving only once when we click the green flag. Go to the ‘Control‘ category, where we have blocks that allow us to repeat a block of code. You’ll see the ‘repeat’ block, where you can enter the number of times you want your code to repeat, and also the ‘forever’ block – the one we want for this project.

Place the ‘forever‘ block below the green flag starting event, with the 2 blocks of code we had added inside it for them to get repeated:

Adding Forever Block to the Code

Repetition blocks run the code that’s within them until a given condition is met. In our case, until we hit the stop button (the red button next to the green flag).

Running our program, we see the fish keeps changing its position on the screen while making bubbles sounds, as intended!

Conclusion

Surprisingly, that’s all there is to it! You now have a simple animation at your fingertips, as well as an understanding of a basic coding algorithm.

However, you don’t have to stop here and can expand this project in numerous ways. Perhaps you’ll want to add more fish to your “tank” that all have different animation behavior. You could also give each fish a unique behavior, such as rotating or flipping direction, whenever they reach the target position. Of course, these principles apply to any kind of animation you might want to try out. Perhaps you want to make a jungle where monkeys move from vine to vine.

The point here is that only your imagination is the limit! Either way, we hope these Scratch fundamentals have set you on the right path to expressing yourself in new ways!

Want to learn more about Scratch animating? Try our complete Scratch Projects – Fish Animation course.

]]>
How to Create a Multi-Platform Idle Clicker Game with Phaser https://gamedevacademy.org/phaser-tutorial-how-to-create-an-idle-clicker-game/ Thu, 23 Jun 2022 13:52:49 +0000 https://gamedevacademy.org/?p=2642 Read more]]> Since the dominance of mobile games in the industry, no genre is more popular than the idle clicker.

In this tutorial, we’re going to use the well-established Phaser 2 framework – which offers cross-platform capabilities – to build an idle clicker game where you “attack” monsters to progress in the game. Of course, we’ll also set up the ability to buy auto-clickers that will “attack” monsters for you as well.

If you’re ready to explore this in-demand genre, let’s learn!

What is an idle click game?

Also known as clicker and incremental games, these type of games have you clicking something repeatedly or idling to gain some form of currency (e.g. cookies, money, energy) which you then use to buy upgrades. It’s a very simple concept at the core, but quite addictive!

Clicker games were first made popular in 2013 with a game called Cookie Clicker. Since then many games have been created in this genre, the themes and flavor of these games vary widely. From cookies to fantasy rpg, sci fi, farming, sand castles, etc.

One such clicker game that I’ve played quite a bit is Clicker Heroes, it’s a fantasy RPG style game where you click various monsters to progress. In this tutorial, we are going to build the foundations of a clicker game similar to Clicker Heroes that you can build upon and add your own style and flair.

Screenshot of Clicker Heroes game

Tutorial source code

You can download the tutorial source code here.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

Getting started

Source Control

The first thing that I do when starting any project is create a folder, and initialize it for git source control. If you don’t already have git, you can download it for your OS from the official site. With any software development, it is critical to have backups. Using source control, specifically git, is a much more robust and safe solution than simply copying or zipping your files periodically. It’s also important to do micro commits, save your progress in very small increments so that you can roll back to any point if you find that you’ve added some new code that is breaking everything. Also it prepares your codebase automatically for upload to a service like github or bitbucket. There are many things beyond simply committing your code that you can do with git, if you are new to git I encourage you to checkout the Git and Github Fundamentals course at Zenva Academy.

After installing git for your system, open the folder you created in a command window, and simply type git init  and it will be ready to go.

Gathering Art

We need to get some sprites for the monsters. A great site to find free art that you can use for your projects is OpenGameArt.org. Much of the artwork is either public domain or licensed to the Creative Commons. A quick search and I’ve found a resource with a variety of monster sprites. This particular set is licensed under CC BY SA 3.0 which basically means that you must give credit to the original authors, and any modifications you make must be shared under the same license. There are other licensing options available to artists, and some do not allow the use of the resources in commercial applications, so be sure to check the licensing on the site.

OpenGameArt.org website with CC-BY-SA 3.0 license highlighted

The monster images that I’ve chosen come in various sizes, each with 4 frames representing various damage states. For this game, we don’t really need the extra damage states, so I have cropped all of the images to just the first frame. For the purposes of this tutorial, I think that 1 image per monster is all that we’ll need. It would be nice if these monsters were animated, but the single image works well for a placeholder right now.

In addition to the monsters, we’ll need some rpg icons for the upgrades and loot. It’s not likely that we’ll use all 496 images in this set, but we can prune the collection later before we are ready to release of the ones that we don’t use. We’ll also need something to use as a background for our world, this forest scene will do nicely.

You’ll find all of the sprites in the assets/images folder of the companion source code to this project. If you’re downloading your own selection of images to use, place them in there as well.

Reminder: Once you’ve added your files, go ahead and commit them to source control.

Setup Phaser

You’ll need to download Phaser, you can either clone the github repo or download the release or use something like Bower to install it. Phaser games are web based games, so first we need a HTML page to host it. Create a file called index.html in the root of your project folder and put this for the contents.

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Click of the Titans</title>
        <style>body {margin: 0;padding: 0;}</style>

        <script src="lib/phaser.min.js"></script>

        <script src="src/game.js"></script>
    </head>
    <body>

    </body>
</html>

Reminder: micro commits, commit your index.html file right now!

You may have noticed that we added a reference to game.js located in the src folder. We don’t have that file yet, let’s create it now.

var game = new Phaser.Game(800, 600, Phaser.AUTO, '');

game.state.add('play', {
    preload: function() {
        game.load.image('skeleton', 'assets/allacrost_enemy_sprites/skeleton.png');
    },
    create: function() {
        var skeletonSprite = game.add.sprite(450, 290, 'skeleton');
        skeletonSprite.anchor.setTo(0.5, 0.5);
    },
    render: function() {
        game.debug.text('Adventure Awaits!', 250, 290);
    }
});

game.state.start('play');

In Phaser, everything starts with an instance of the Game class. We are passing it the width and height of the game screen that we want as well as the renderer. Phaser supports both Canvas and WebGL based rendering, Phaser.AUTO tells it to pick based on what’s available in the browser (WebGL if available).

In the preload phase of our “play” game state we are going to load up one of our monster images so that we can have something to show other than a blank screen. Each state in Phaser has several phases in its lifecycle, and preload  is one of the first.

Next up is create , after assets are loaded, it’s safe to create sprites using them. The Sprite is one of the main game objects in Phaser, most everything that you create in the game world will generally have a sprite involved. Adding a sprite takes a few parameters: the x & y coordinates of where it should be located on the screen, and a key that can be used to reference it later. We’re also going to change the anchor for the sprite to the center of the image. The anchor is the point in space where the sprite is positioned or rotated around. By default the anchor is set to the top left most point of the image 0, 0  I ususally like to work with the anchor in the center of the image, because if I want to spin the sprite, I want it to spin around the center instead of the top left (like a wheel).

Finally, render  is one of the last phases in the lifecycle, it happens after update (we don’t need update for this game). Most of the time Phaser handles rendering internally, but for now we’ll just add some fun text to make our screen more exciting.

Reminder: now’s a great time to commit your file!

Running your game

We’re almost ready to fire up Phaser and see what we have, except that it’s not just as simple as clicking on index.html and loading it in your browser. Due to security restrictions the browser will not allow you to load assets asynchronously. For that reason you need to run a server, or load the files in a different manner. PhotonStorm has posted an article listing several options for servers, however if loading the software to run a server isn’t something that you are interested in, I have another option. If you are running Google Chrome, you can actually setup your game to run as a Chrome application quite easily. Doing this elevates your game out of the browser sandbox (and actually gives you a set of APIs to access native systems such as the file system and networking) and these restrictions no longer apply. There are however a different set of security restrictions involving resources located outside of the files packaged with the app. Depending on how you want to distribute your final product, creating a Chrome app may be a great choice. I’ll include the basic files needed to launch this as a Chrome App, if you are interested in learning more I encourage you to read more at the official documentation.

Once you launch your game, you should see this:

New Phaser game with Skeleton and "Adventure Awaits" message

Now you know that Phaser is up and running. We’ve loaded a sprite and written a bit of text to the screen! We’re almost done 🙂 … well not quite, but we’re ready to start actually making a game.

Setting the Stage

The first thing that we want to do is get rid of that boring black background and bring our world to life. In the preload  method, add all of the images that make up the forest background. There happen to be four different images for this because it is designed to be used as a parallax scrolling background. Typically this type of background is used in side scrolling platformer games, but it gives us the option of doing an animation effect later.

this.game.load.image('forest-back', 'assets/parallax_forest_pack/layers/parallax-forest-back-trees.png');
this.game.load.image('forest-lights', 'assets/parallax_forest_pack/layers/parallax-forest-lights.png');
this.game.load.image('forest-middle', 'assets/parallax_forest_pack/layers/parallax-forest-middle-trees.png');
this.game.load.image('forest-front', 'assets/parallax_forest_pack/layers/parallax-forest-front-trees.png');

In the create  method since we have 4 different images that make up the background, we’ll create a Group of TileSprite objects. Using a javascript array of the image keys, we can use the built in forEach method to quickly and elegantly create all four in the correct order.

var state = this;

this.background = this.game.add.group();
// setup each of our background layers to take the full screen
['forest-back', 'forest-lights', 'forest-middle', 'forest-front']
    .forEach(function(image) {
        var bg = state.game.add.tileSprite(0, 0, state.game.world.width,
            state.game.world.height, image, '', state.background);
        bg.tileScale.setTo(4,4);
    });

A TileSprite is a type of image that is meant to be repeated or tiled over a large area. To create one you need to pass it not only the x & y coordinates, but also a width and height for how big the area that it needs to cover should be. Just like the Sprite, you give it the image key to use. The final parameter that we pass it is our group, so that each one is automatically added to the background group. We want the background to cover the whole screen, so we’ll pass in the game world’s width and height. Also, in this case, our image isn’t really meant to be tiled like a mosaic, so we’ll scale the tiling so that it looks more like one image (play with the scale numbers to see what I mean about the tiling).

Let’s take a moment to talk about the group that we created. Groups are an extremely powerful feature of Phaser that are capable of a whole lot more than just the name suggests. At the very base level, they act as a collection, sort of like an array, and they have several methods available for traversing and manipulating the items in the collection. Another important aspect of groups is that the children of the group are positioned, rotated, and scaled all relative to the group itself. If we set group.x = 10; then it will move all of the children over by 10 as well. The position of the children is relative meaning that if a child item also has it’s x coord set to 10, then it will actually be placed at x 20 on the screen (assuming that the group itself is not a child of another parent that isn’t at 0,0). We will use groups extensively in our game and I encourage you to read the documentation to find out more about all of the methods and properties that are available.

Reminder: time to commit your files!

The Army of Darkness

After setting the stage, the next thing we need is something to attack. Time to unleash the horde of monsters that we’ve collected. In order to be able to use all of our monsters, we need to load each image. Let’s change the preload  section of our play  state to do just that. Each one needs a key to reference it by, and the path to the image file.

    this.game.load.image('aerocephal', 'assets/allacrost_enemy_sprites/aerocephal.png');
    this.game.load.image('arcana_drake', 'assets/allacrost_enemy_sprites/arcana_drake.png');
    this.game.load.image('aurum-drakueli', 'assets/allacrost_enemy_sprites/aurum-drakueli.png');
    this.game.load.image('bat', 'assets/allacrost_enemy_sprites/bat.png');
    this.game.load.image('daemarbora', 'assets/allacrost_enemy_sprites/daemarbora.png');
    this.game.load.image('deceleon', 'assets/allacrost_enemy_sprites/deceleon.png');
    this.game.load.image('demonic_essence', 'assets/allacrost_enemy_sprites/demonic_essence.png');
    this.game.load.image('dune_crawler', 'assets/allacrost_enemy_sprites/dune_crawler.png');
    this.game.load.image('green_slime', 'assets/allacrost_enemy_sprites/green_slime.png');
    this.game.load.image('nagaruda', 'assets/allacrost_enemy_sprites/nagaruda.png');
    this.game.load.image('rat', 'assets/allacrost_enemy_sprites/rat.png');
    this.game.load.image('scorpion', 'assets/allacrost_enemy_sprites/scorpion.png');
    this.game.load.image('skeleton', 'assets/allacrost_enemy_sprites/skeleton.png');
    this.game.load.image('snake', 'assets/allacrost_enemy_sprites/snake.png');
    this.game.load.image('spider', 'assets/allacrost_enemy_sprites/spider.png');
    this.game.load.image('stygian_lizard', 'assets/allacrost_enemy_sprites/stygian_lizard.png');

In the create  method is where we’ll want to create Sprite objects for these images so that they can exist in the game world. Much like the background images, it’s faster and easier to read if we put all the information that we need to load into an array. This time however, we need more than just the image key. We’re going to want to display the name of the monster on the screen below it, so that the player knows what they are facing. To do this we’ll create an array of objects that has a name property suitable for display, as well as the image key.

var monsterData = [
    {name: 'Aerocephal', image: 'aerocephal'},
    {name: 'Arcana Drake', image: 'arcana_drake'},
    {name: 'Aurum Drakueli', image: 'aurum-drakueli'},
    {name: 'Bat', image: 'bat'},
    {name: 'Daemarbora', image: 'daemarbora'},
    {name: 'Deceleon', image: 'deceleon'},
    {name: 'Demonic Essence', image: 'demonic_essence'},
    {name: 'Dune Crawler', image: 'dune_crawler'},
    {name: 'Green Slime', image: 'green_slime'},
    {name: 'Nagaruda', image: 'nagaruda'},
    {name: 'Rat', image: 'rat'},
    {name: 'Scorpion', image: 'scorpion'},
    {name: 'Skeleton', image: 'skeleton'},
    {name: 'Snake', image: 'snake'},
    {name: 'Spider', image: 'spider'},
    {name: 'Stygian Lizard', image: 'stygian_lizard'}
];

After that, we’ll need to create the actual sprites for them in order to render them in the game world. Time for another group!

this.monsters = this.game.add.group();

var monster;
monsterData.forEach(function(data) {
    // create a sprite for them off screen
    monster = state.monsters.create(1000, state.game.world.centerY, data.image);
    // center anchor
    monster.anchor.setTo(0.5);
    // reference to the database
    monster.details = data;

    //enable input so we can click it!
    monster.inputEnabled = true;
    monster.events.onInputDown.add(state.onClickMonster, state);
});

When it comes to sprites, groups have a special method create that we can use. For other game objects we need to create them using the normal game factories, and add them as children to the group, the create method only works for sprites. It takes the normal sprite parameters; position and image key, but also lets you pass in a flag as to whether or not the sprite “exists”. This parameter is most often used in object pooling, which we’ll cover a bit later. Each sprite we’ll set the anchor to the center, and set a reference to our monsterData item so that we can reference it later (to display the name).

We’re also going to want to be able to click the monsters (it’s a *click*er game after all), we can tell Phaser to register click events by setting inputEnabled to true. Doing so will enable several input events, we’re interested in what happens when we click the mouse button down (or tap it). For that we’ll tell it to use the onClickMonster  method of our state, and that it should be called in the context of our state (javascript “this”). We haven’t created that method yet, we’ll do that in a minute.

In this game, we only ever want to face one monster at a time, so we need a reference to the monster that we are currently facing. Another cool feature of a group is that we can let Phaser randomly select one using getRandom() . Then set the position of the monster to roughly the center of the screen, a little off so that we have room for some other things later.

this.currentMonster = this.monsters.getRandom();
this.currentMonster.position.set(this.game.world.centerX + 100, this.game.world.centerY);

Next we can modify our render method so that we can show the name of the monster that we are up against.

render: function() {
    game.debug.text(this.currentMonster.details.name,
        this.game.world.centerX - this.currentMonster.width / 2,
        this.game.world.centerY + this.currentMonster.height / 2);
}

Finally, we need to add that onClickMonster  handler so that something happens when we click them. For now, we’ll just change out the monster on each click so that we can test running through our list (epic insta-kill!). Each click we’ll set the currentMonster to another random one, and position it in the center of the screen. We’ll move the other monster off screen so that we can’t see it at the same time.

onClickMonster: function() {
    // reset the currentMonster before we move him
    this.currentMonster.position.set(1000, this.game.world.centerY);
    // now pick the next in the list, and bring him up
    this.currentMonster = this.monsters.getRandom();
    this.currentMonster.position.set(this.game.world.centerX + 100, this.game.world.centerY);
},

Reminder: time to commit your files again!

Phaser 3 game with tentacle dragon enemy in scene

Clicking For Great Justice

Obviously just clicking to cycle through the monsters isn’t much of a gameplay element. Instead we need to simulate RPG combat by clicking and dealing damage to the monsters. In order to deal damage, we need to know something about our player. The main hero of this game isn’t directly represented by a sprite on the screen, so we will just create a plain javascript object to hold useful information about them. Add this to the bottom of the create phase:

// the main player
this.player = {
    clickDmg: 1,
    gold: 0
};

Also in order to be able to kill the monsters, they need to have some health to damage. Let’s go back to our monster database from before, and add a maxHealth attribute to each one. For now, for the values of maxHealth, I’ve just chosen somewhat arbitrary numbers, by looking at the sprite and just making a few tougher than the others. Later we can get deeper into gameplay and balance out the toughness of the monsters. I also adjusted the spacing so that it looks a little more like a table and is easier to edit.

var monsterData = [
    {name: 'Aerocephal',        image: 'aerocephal',        maxHealth: 10},
    {name: 'Arcana Drake',      image: 'arcana_drake',      maxHealth: 20},
    {name: 'Aurum Drakueli',    image: 'aurum-drakueli',    maxHealth: 30},
    {name: 'Bat',               image: 'bat',               maxHealth: 5},
    {name: 'Daemarbora',        image: 'daemarbora',        maxHealth: 10},
    {name: 'Deceleon',          image: 'deceleon',          maxHealth: 10},
    {name: 'Demonic Essence',   image: 'demonic_essence',   maxHealth: 15},
    {name: 'Dune Crawler',      image: 'dune_crawler',      maxHealth: 8},
    {name: 'Green Slime',       image: 'green_slime',       maxHealth: 3},
    {name: 'Nagaruda',          image: 'nagaruda',          maxHealth: 13},
    {name: 'Rat',               image: 'rat',               maxHealth: 2},
    {name: 'Scorpion',          image: 'scorpion',          maxHealth: 2},
    {name: 'Skeleton',          image: 'skeleton',          maxHealth: 6},
    {name: 'Snake',             image: 'snake',             maxHealth: 4},
    {name: 'Spider',            image: 'spider',            maxHealth: 4},
    {name: 'Stygian Lizard',    image: 'stygian_lizard',    maxHealth: 20}
];

Phaser sprites come with both Health and LifeSpan components built in that provide all of the features that we need in order to get combat working. They provide us with a damage()  and heal()  method and take into account health and maxHealth in those methods. When you apply damage and the health drops to 0 (or below) it will automatically call kill()  and fire the onKilled  event. Similarly, there is a  revive()  method that allows you to bring a monster back from the dead fully healed. When a monster is revived, it fires the onRevived event. We will hook into those events to drop loot and change monsters. Inside the loop that creates the monster sprites, let’s set the health component based on the value in our data array.

// use the built in health component
monster.health = monster.maxHealth = data.maxHealth;

// hook into health and lifecycle events
monster.events.onKilled.add(state.onKilledMonster, state);
monster.events.onRevived.add(state.onRevivedMonster, state);

Next update the onClickMonster  method to deal damage to the monster based on the player’s clickDmg  attribute. When the monster’s health reaches 0, it will be killed.

onClickMonster: function(monster, pointer) {
    // apply click damage to monster
    this.currentMonster.damage(this.player.clickDmg);
}

Clicking on a monster will do damage, but it’s important to provide feedback to the player that this is happening. No one likes to click things and see nothing happen, it feels broken. Also, I think it’s time to get rid of the debug text and use an actual text object to display the monster’s name and health. Add these 2 Text objects to your create method. Again we’ll create another group so that moving the monster information around is easy. Creating Text objects is relatively straight forward, like most display objects you provide it the position on the screen (or relative to its parent), but instead of an image key, you pass it the string that you want to display. Optionally you can send in font styling data to change how it’s displayed. This font style information is very similar to standard HTML Canvas fonts.

this.monsterInfoUI = this.game.add.group();
this.monsterInfoUI.position.setTo(this.currentMonster.x - 220, this.currentMonster.y + 120);
this.monsterNameText = this.monsterInfoUI.addChild(this.game.add.text(0, 0, this.currentMonster.details.name, {
    font: '48px Arial Black',
    fill: '#fff',
    strokeThickness: 4
}));
this.monsterHealthText = this.monsterInfoUI.addChild(this.game.add.text(0, 80, this.currentMonster.health + ' HP', {
    font: '32px Arial Black',
    fill: '#ff0000',
    strokeThickness: 4
}));

Back in our onClickMonster  event, we want to update the text now to reflect the monster’s new health.

// update the health text
this.monsterHealthText.text = this.currentMonster.alive ? this.currentMonster.health + ' HP' : 'DEAD';

When a monster is killed it fires the onKilled  event, we want to push it back off screen and then select a new monster and revive them. The revive method optionally takes a health parameter that will set the health of the monster to the value provided. It then sets alive, visible, and exists to true, and then fires the onRevived event. Add the onKilledMonster  method to our state now.

onKilledMonster: function(monster) {
    // move the monster off screen again
    monster.position.set(1000, this.game.world.centerY);

    // pick a new monster
    this.currentMonster = this.monsters.getRandom();
    // make sure they are fully healed
    this.currentMonster.revive(this.currentMonster.maxHealth);
},

When a monster is revived, we want to get them into position on the screen, and reset the monster display text to reflect the new monster. After the kill handler, let’s add the onRevivedMonster  event handler to our state as well. Here we move the monster to the center area of the screen and update our text objects to reflect the new information.

onRevivedMonster: function(monster) {
    monster.position.set(this.game.world.centerX + 100, this.game.world.centerY);
    // update the text display
    this.monsterNameText.text = monster.details.name;
    this.monsterHealthText.text = monster.health + 'HP';
},

Ok, now we can see what is happening, and that is good. It still doesn’t quite feel exciting enough though, I think we can add more. For every click, let’s display the damage that we’re doing. For that, we’ll want to create a pool of text objects. Each click we need to display the damage number for a short period and then it should disappear. Instead of creating a new text object for each click (which we could do), it’s better to create a bunch up front and just change the properties. The reason is that in almost all programming situations, especially in JavaScript, creating new objects is an expensive operation. Not something that you want to be doing a lot of every frame. Let’s create a pool of about 50 text objects (I think I can do 30 clicks / second so that’s a decent buffer). The following should go in your create  method.

this.dmgTextPool = this.add.group();
var dmgText;
for (var d=0; d<50; d++) {
    dmgText = this.add.text(0, 0, '1', {
        font: '64px Arial Black',
        fill: '#fff',
        strokeThickness: 4
    });
    // start out not existing, so we don't draw it yet
    dmgText.exists = false;
    dmgText.tween = game.add.tween(dmgText)
        .to({
            alpha: 0,
            y: 100,
            x: this.game.rnd.integerInRange(100, 700)
        }, 1000, Phaser.Easing.Cubic.Out);

    dmgText.tween.onComplete.add(function(text, tween) {
        text.kill();
    });
    this.dmgTextPool.add(dmgText);
}

As you can see in order to create a pool of damage text objects to use we didn’t have to do anything special. We used the groups that we already know and love. A standard for loop will help us create 50 of them, and we’ll set them all to exists = false  so that they don’t render on the screen until we tell them to. Next, we’re going to add another super powerful tool in Phaser’s arsenal, a Tween. A tween allows you to modify various properties of an object over time. It uses one of several mathematical equations to “ease” these values from start to finish and create animation effects. For the damage text, we want it to fly out from where it was clicked in a random direction and also fade out so that by the time that it reaches its destination, it can no longer be seen. In the to  method of the tween, we set the final values that we want the alpha, y and x properties of the object to be, the starting values will be the values of the object when the tween begins. The second parameter is the time that it should take to complete the tween, we’ll set it to 1000 (the value is in milliseconds, so 1 second). The final parameter is the Easing equation that we want to use. When a tween animation is completed, an event is fired, we can hook into there and kill()  the text object (effectively setting it back to exists = false ).

Now we’ll turn these on so that clicking to do damage is really exciting. Every time we click, we’ll grab the first available dmgText object (i.e. not killed) from the group using getFirstExists(false) , the false tells the group that we want one that doesn’t exist. Then update the text to reflect the current click damage. We need to reset the alpha property from when the tween had adjusted it, and we want to start this one at the spot where the player clicked. Then we’ll start the tween again, and get our animation.

// grab a damage text from the pool to display what happened
var dmgText = this.dmgTextPool.getFirstExists(false);
if (dmgText) {
    dmgText.text = this.player.clickDmg;
    dmgText.reset(pointer.positionDown.x, pointer.positionDown.y);
    dmgText.alpha = 1;
    dmgText.tween.start();
}

Reminder: commit that code!

Demonic Essence enemy with damage displayed from attack

Phat Lootz

Killing monsters isn’t something that the player does just for sport, they’re in it for the rewards of gold and treasure. We need to drop some loot when the monster dies, let’s add a gold coin to our images loading in the preload method.

this.game.load.image('gold_coin', 'assets/496_RPG_icons/I_GoldCoin.png');

To start with, every monster will drop a single gold coin when it dies. The player will need to click on them to collect them, and so there could be quite a few laying around before they decide to do that. To create a pool of gold coins, again we’ll utilize the group. This time, since we’re creating a pool of sprites, we can use a special method called createMultiple. This method is very similar to the create  method in that it only creates sprites, for this one, it takes a new parameter, the number that you want to create. Since we’re not using a for loop this time to create them, we need a way to setup some defaults without having to loop through our newly created group, for that, we have another method called setAll. It takes the property and value and applies that to each object in the group. We also want to register the onInputDown handler, since adding a handler to an event is a method, we use callAll to execute the events.onInputDown.add  method on each child of the group.

// create a pool of gold coins
this.coins = this.add.group();
this.coins.createMultiple(50, 'gold_coin', '', false);
this.coins.setAll('inputEnabled', true);
this.coins.setAll('goldValue', 1);
this.coins.callAll('events.onInputDown.add', 'events.onInputDown', this.onClickCoin, this);

Again we need feedback in the UI so that we know that we are collecting gold. Add this text object to the create  method.

this.playerGoldText = this.add.text(30, 30, 'Gold: ' + this.player.gold, {
    font: '24px Arial Black',
    fill: '#fff',
    strokeThickness: 4
});

Now we can add our click handler for the coins. When a coin is clicked, the goldValue  of the coin is added to the player’s gold. We also have to update the UI so that we can see the change. Finally, we kill the coin so that it disappears back into our pool for reuse.

onClickCoin: function(coin) {
    // give the player gold
    this.player.gold += coin.goldValue;
    // update UI
    this.playerGoldText.text = 'Gold: ' + this.player.gold;
    // remove the coin
    coin.kill();
}

Next we need to add to the onKilledMonster  event so that we can actually drop these coins. Much like the dmgText objects, we’ll grab the first available coin and bring it to life positioning it somewhere randomly in the center-ish of the screen. We update the goldValue (even though we’re just setting it to 1 now) so that in the future we can drop different amounts of gold as we progress.

var coin;
// spawn a coin on the ground
coin = this.coins.getFirstExists(false);
coin.reset(this.game.world.centerX + this.game.rnd.integerInRange(-100, 100), this.game.world.centerY);
coin.goldValue = 1;

Dune Crawler enemy with Gold amount displayed in the upper left corner

As I mentioned earlier, the player has to click on the coins in order to collect them. After a few kills, if they don’t do that, the floor will become quite littered with gold. While piles of cash is always fun, eventually we might run out of new coins to spawn from our pool. What we need to do is automatically collect gold for the player after a short time so that the world doesn’t become cluttered.

To accomplish this, Phaser has a Timer object that we can use to create our own custom timed events. If the coin sits there not being clicked for 3 seconds, then we’ll “click” it for them, by firing the same onClickCoin  method that we use when they do click it. The timer event takes the duration, the handler, the context that the handler should fire in, and any other additional parameters that should be passed to the handler.

this.game.time.events.add(Phaser.Timer.SECOND * 3, this.onClickCoin, this, coin);

Since we are going to be calling the onClickCoin  method when the timer completes in addition to when the coin is clicked, we need to test and make sure that we don’t call it twice. If the player clicks the coin before the timeout, the timeout will still fire, but the gold will already be collected, and the coin already killed. We can add a simple test at the top of the function to make sure that when we collect this coin it is still alive.

if (!coin.alive) {
    return;
}

Reminder: commit the source, save your work!

Upgrades

I’m sure by now you’re tired of doing just 1 point of damage every click, and we’ve got nothing to spend our precious gold on! Time to create some upgrades. The upgrades menu is going to be a box, with some buttons inside that you can click on to buy things. For the background of the upgrades menu, we could use more art from the web, or create an image ourselves in a paint program, but instead we can utilize the HTML5 Canvas to build it for us. Instead of loading an image, Phaser has an object called BitmapData that creates a canvas for us. The result of the canvas can then be used in place of an image on a sprite. Instead of setting the key when it is loaded like with an image, instead we need to manually add it to Phaser’s asset cache. In the preload  method we will generate images (colored rectangles) for the background of the upgrades menu and also the buttons.

// build panel for upgrades
var bmd = this.game.add.bitmapData(250, 500);
bmd.ctx.fillStyle = '#9a783d';
bmd.ctx.strokeStyle = '#35371c';
bmd.ctx.lineWidth = 12;
bmd.ctx.fillRect(0, 0, 250, 500);
bmd.ctx.strokeRect(0, 0, 250, 500);
this.game.cache.addBitmapData('upgradePanel', bmd);

var buttonImage = this.game.add.bitmapData(476, 48);
buttonImage.ctx.fillStyle = '#e6dec7';
buttonImage.ctx.strokeStyle = '#35371c';
buttonImage.ctx.lineWidth = 4;
buttonImage.ctx.fillRect(0, 0, 225, 48);
buttonImage.ctx.strokeRect(0, 0, 225, 48);
this.game.cache.addBitmapData('button', buttonImage);

For the upgrades menu, we don’t need something as heavy as a sprite (with all the health and other stuff). Instead for things that are going to be purely user interface objects, it is better to use a Image. An Image object has the same transform information (position, scale, rotation) just not all the extra things that a sprite does. Instead of passing in an image key, we’ll pull the image out of the cache that we put it into earlier. The menu panel will also contain a group for the buttons, that way all of the buttons can follow the menu and be relative to its transforms. Because of the border on the background image, we’ll move the button group in a little bit.

this.upgradePanel = this.game.add.image(10, 70, this.game.cache.getBitmapData('upgradePanel'));
var upgradeButtons = this.upgradePanel.addChild(this.game.add.group());
upgradeButtons.position.setTo(8, 8);

Stygian Lizard enemy with newly added upgrade frame

Our first upgrade will be to the click damage so we can start killing faster. Let’s pick an icon from our library and add that to our image load.

this.game.load.image('dagger', 'assets/496_RPG_icons/W_Dagger002.png');

Phaser has another object in its bag of tricks, the Button object. A button is a subclass of an Image object that is designed to handle being clicked out of the box. It supports 4 different button states: Out, Over, Down, and Up. You can provide a spritesheet image with different looks for each of these states, it can make the button appear to actually be “pressed” for example, or change color when you hover over top of it. I’ve only generated a single background frame for our buttons for now, it still works fine without the other images. For the button we are going to add the icon, a label for what the upgrade is, and another text to display the gold cost for upgrading.

var button;
button = this.game.add.button(0, 0, this.game.cache.getBitmapData('button'));
button.icon = button.addChild(this.game.add.image(6, 6, 'dagger'));
button.text = button.addChild(this.game.add.text(42, 6, 'Attack: ' + this.player.clickDmg, {font: '16px Arial Black'}));
button.details = {cost: 5};
button.costText = button.addChild(this.game.add.text(42, 24, 'Cost: ' + button.details.cost, {font: '16px Arial Black'}));
button.events.onInputDown.add(this.onUpgradeButtonClick, this);

After creating the button, then add it to the buttons group.

upgradeButtons.addChild(button);

For now our button handler simply needs to test the one button that we have. First we’ll check that we can afford to purchase the upgrade, if we can then we’ll go through with it. We need to adjust the player’s gold from the cost, and update the UI to reflect that change. We also need to improve the player’s clickDmg attribute, and update the text on the button. Now we can spend our hard earned loot to get stronger!

onUpgradeButtonClick: function(button, pointer) {
    if (this.player.gold - button.details.cost >= 0) {
        this.player.gold -= button.details.cost;
        this.playerGoldText.text = 'Gold: ' + this.player.gold;
        this.player.clickDmg++;
        button.text.text = 'Attack: ' + this.player.clickDmg;
    }
}

Aerocephal enemy with Attack 21 as an upgrade

Now it’s time to add the second type of upgrade, the DPS upgrade. Until now the only way to deal damage to monsters is by directly clicking on them. While this is an important mechanic in our game, it can get tedious after a while. This is the part that makes this type of game fall into the “idle” genre. Players will continue to progress and deal damage to monsters even when they are not actively clicking them.

In order to add a new button, we need to repeat what we have, and change the effect of purchasing the upgrade. Doing this one button at a time will get unruly after a bit, so we want to create a database array of upgrades, just like we have for monsters. We’ll need the icon to display, the name of the upgrade, the level for the number of times that it has been upgraded, the cost in gold to upgrade, and a callback function that we can fire to provide a different effect for each upgrade.

var upgradeButtonsData = [
    {icon: 'dagger', name: 'Attack', level: 1, cost: 5, purchaseHandler: function(button, player) {
        player.clickDmg += 1;
    }},
    {icon: 'swordIcon1', name: 'Auto-Attack', level: 0, cost: 25, purchaseHandler: function(button, player) {
        player.dps += 5;
    }}
];

We need to add the dps property to our player, so that our purchase handler can take effect.

this.player = {
    clickDmg: 1,
    gold: 0,
    dps: 0
};

Now we can loop through our data and create all of our upgrade buttons in bulk. Because the buttons are about 48 pixels high, we’ll separate each one by 50. Instead of hard coding the text strings and icon, they will be populated from the data.

var button;
upgradeButtonsData.forEach(function(buttonData, index) {
    button = state.game.add.button(0, (50 * index), state.game.cache.getBitmapData('button'));
    button.icon = button.addChild(state.game.add.image(6, 6, buttonData.icon));
    button.text = button.addChild(state.game.add.text(42, 6, buttonData.name + ': ' + buttonData.level, {font: '16px Arial Black'}));
    button.details = buttonData;
    button.costText = button.addChild(state.game.add.text(42, 24, 'Cost: ' + buttonData.cost, {font: '16px Arial Black'}));
    button.events.onInputDown.add(state.onUpgradeButtonClick, state);

    upgradeButtons.addChild(button);
});

When we click an upgrade button now we need to increase its level and update the text to reflect the change. Then we’ll execute the purchaseHandler callback in the context of the state, passing the button and player along to the handler.

onUpgradeButtonClick: function(button, pointer) {
    if (this.player.gold - button.details.cost >= 0) {
        this.player.gold -= button.details.cost;
        this.playerGoldText.text = 'Gold: ' + this.player.gold;
        button.details.level++;
        button.text.text = button.details.name + ': ' + button.details.level;
        button.details.purchaseHandler.call(this, button, this.player);
    }
}

Ok, so we’re increasing both attack and dps (damage per second), but we haven’t setup dps to do anything yet. For dps to make sense, if we have 1 dps then after 1 second has passed we do 1 damage. Waiting the full second to apply any damage at all though is too choppy and slow. Instead we’ll update at 100ms (10 times a second). So, in order to apply 1 damage after 1 second, then we need to apply 0.10 damage every 100ms. Similar to the timer event that we used for the gold coins, there are also loop events that will repeat and call the handler at the duration over and over.

// 100ms 10x a second
this.dpsTimer = this.game.time.events.loop(100, this.onDPS, this);

Our dps handler is going to get called every 100ms whether we have upgraded or not. So we check if we have something to do first, if so, then make sure the monster is still alive to apply the damage. Then we’ll damage the monster and update the text to reflect the monster’s health. I don’t really want to display the decimals that might occur on the monster health from doing 10% damage, so we’ll round it for the display (not the actual health).

onDPS: function() {
    if (this.player.dps > 0) {
        if (this.currentMonster && this.currentMonster.alive) {
            var dmg = this.player.dps / 10;
            this.currentMonster.damage(dmg);
            // update the health text
            this.monsterHealthText.text = this.currentMonster.alive ? Math.round(this.currentMonster.health) + ' HP' : 'DEAD';
        }
    }
}

Reminder: don’t forget to commit!

Progression

Killing the same monsters over and over is boring. We need to keep increasing the difficulty so that the players can face a challenge and progress. Let’s add some world level stats to the preload  section.

// world progression
this.level = 1;
// how many monsters have we killed during this level
this.levelKills = 0;
// how many monsters are required to advance a level
this.levelKillsRequired = 10;

Each time we kill a monster now, we need to increase the kills stat. We also need to upgrade the monster’s health based on the level. With increased risk, comes increased reward, and we’ll also modify the coin value based on the world level as well. After 10 monsters have been killed, then we can progress to the next level.

onKilledMonster: function(monster) {
    // move the monster off screen again
    monster.position.set(1000, this.game.world.centerY);

    var coin;
    // spawn a coin on the ground
    coin = this.coins.getFirstExists(false);
    coin.reset(this.game.world.centerX + this.game.rnd.integerInRange(-100, 100), this.game.world.centerY);
    coin.goldValue = Math.round(this.level * 1.33);
    this.game.time.events.add(Phaser.Timer.SECOND * 3, this.onClickCoin, this, coin);

    this.levelKills++;

    if (this.levelKills >= this.levelKillsRequired) {
        this.level++;
        this.levelKills = 0;
    }

    // pick a new monster
    this.currentMonster = this.monsters.getRandom();
    // upgrade the monster based on level
    this.currentMonster.maxHealth = Math.ceil(this.currentMonster.details.maxHealth + ((this.level - 1) * 10.6));
    // make sure they are fully healed
    this.currentMonster.revive(this.currentMonster.maxHealth);
}

Since we’ll be getting a lot more money now, we also need to adjust the upgrade prices.

onUpgradeButtonClick: function(button, pointer) {
    // make this a function so that it updates after we buy
    function getAdjustedCost() {
        return Math.ceil(button.details.cost + (button.details.level * 1.46));
    }

    if (this.player.gold - getAdjustedCost() >= 0) {
        this.player.gold -= getAdjustedCost();
        this.playerGoldText.text = 'Gold: ' + this.player.gold;
        button.details.level++;
        button.text.text = button.details.name + ': ' + button.details.level;
        button.costText.text = 'Cost: ' + getAdjustedCost();
        button.details.purchaseHandler.call(this, button, this.player);
    }
}

Finally, we’ll add the level information to the UI so that the player knows how they are doing. By now adding text objects to reflect this information should be old hat to you!

// setup the world progression display
this.levelUI = this.game.add.group();
this.levelUI.position.setTo(this.game.world.centerX, 30);
this.levelText = this.levelUI.addChild(this.game.add.text(0, 0, 'Level: ' + this.level, {
    font: '24px Arial Black',
    fill: '#fff',
    strokeThickness: 4
}));
this.levelKillsText = this.levelUI.addChild(this.game.add.text(0, 30, 'Kills: ' + this.levelKills + '/' + this.levelKillsRequired, {
    font: '24px Arial Black',
    fill: '#fff',
    strokeThickness: 4
}));

We also need to update the level text when it changes inside the  onKilledMonster  method.

this.levelText.text = 'Level: ' + this.level;
this.levelKillsText.text = 'Kills: ' + this.levelKills + '/' + this.levelKillsRequired;

Spider enemy with various upgrades in Phaser 3 game

Reminder: commit commit commit

Finished the basics, what’s next?

What we’ve created here is a complete idle clicker RPG. Well, complete as in it’s playable. There’s still tons left to do in order to get this game turned into something that is really fun. In game development, they say that the last 10% of the work is the last 90% of your time. We’re pretty much 90% done I think 🙂

Here’s a list of things that would be great to add: (possibly in future tutorials)

  • monsters with animation
  • sounds & music!
  • more upgrades
  • critical hits
  • boss monsters
  • timed boost powers
  • different world backgrounds
  • achievements
  • leader boards

I hope that you have enjoyed this tutorial and making this game!

Please leave comments and questions below, I welcome any feedback and would love to see your games too!

]]>