Where's My Lunch? - January Devlog Update

Six months ago the game “Where’s My Lunch?” was born out of the Game Makers Toolkit GameJam. The original game idea was to use bombs to move the player object around the scene to some sort of goal - trying to play on the jam’s theme of “Out of Control.” Nothing too clever, but physics and explosions are generally good fun and it seemed like a good starting point.

Every game or project I’d ever made in Unity was 3D and WML was no different. It started as a 3D game with the simple colored cubes and spheres standing pretending to be game art. It was clumsy and basic but still, it felt like it had some potential.

That first evening, I started to work on the art style. I needed something simple, quick, and hopefully not too hard to look at… After bumping around with a few ideas, I downloaded FireAlpaca and starting drawing stick figures. For the life of me, I can’t remember why… I just did. I tossed on a hat to add a little character and Hank was born and I was on my way to making my first ever 2D game!

Early 3d Prototype

Early 3d Prototype

With great input from viewers as I streamed the game’s progress, I added gravity wells and portals to the project to add even more physics-based chaos to the game. With the help of a clumsy but effective save system, I created a dozen playable levels. I was even able to add a sandbox level which was another suggestion from a viewer.

Results out of over 5000 submissions

Results out of over 5000 submissions

With time running out on the 48 hour game jam, I did my best to fix a few bugs, pushed a build to Itch, and submitted my efforts to the game jam. I’d spent somewhere in the neighborhood of 20 hours working on the game and I was pretty content with the results.

The game finished in the top 10% of over 5000 games submitted, which while we always dream higher, I have to admit felt pretty darn good. With the results posted, I mentally closed up the project and didn’t intend to come back to it. I’d learned a lot and had some fun. What more was there to do with the game?

Where’s My Lunch?

I still dream of Making this game

I still dream of Making this game

Like so many others I’ve had projects come and go. With most not getting finished due to over scoped game ideas and lack of time to make those ideas a reality. This is a lesson I continue to struggle to learn…

A few months after the game jam, the idea came along to polish and publish a small game while making video content along the way. I loved it! It seemed like a perfect project.

I spent much of October and November planning out the project with an eye to keeping the scope small but still adding ideas and topics that might make useful videos and hopefully a more engaging game. I started work on a notion page (which I much prefer to Trello) trying to find the balance between tasks that were too big or too small. And to be honest, I’ve never forced myself to fully plan out a game to this level of detail.

The planning wasn’t particularly fun, I had to actively fight the urge to open Unity and just get to work… I didn’t list absolutely everything that needed to be done, but I got most of it and I think the result was more than worth the effort.

I knew the scope of the game. I knew what I needed to do next. And in some way, I had a contract with myself as to what I was making with clear limits on the project.

All of this had me hopeful that the project will have a different ending than so many of my past projects.

Progress?

With the planning was done it was time for the fun part. Digging into the code!

Most of the early hours spent with the code didn’t make a big difference in the appearance or even the player experience. Much of that early time was spent shoring up the underlying framework, making code more generic and more robust. I wanted to be able to add mechanics and features without breaking the game with each addition. Yes, we’ve all been there. While maybe not the highest standard, I’ve come to judge my own work by what needs to happen to add a new feature, how long that takes, and how much else breaks in the process.

Does adding a new level to the game require rewriting game manager code? Or manually adding a new UI button? Or can I simply add a game level object to a list and the game handles the rest?

What about adding the ability to change the color of an object when the player selects it? Does that break the placement system? Does that result in messy code that will need to be modified for each new game item? Or can it be done by creating a simple, clean and easy to use component that can be added to any and all selectable objects?

Holding myself to this standard and working in a small scoped game has felt really good. It hasn’t always been easy AND importantly I don’t think I could have held myself to that standard during the game jam. There simply wasn’t time.

For example, during the game jam I wanted players to be able to place the portals to solve a level but in order for a portal to work it needs to have a connection to another portal… The simplest solution was to create a prefab that was a parent object with two children portals. This meant when they were added they could already be connected. And while this worked it also created all kinds of messy code to handle this structure. Which meant I had all these “if the object is a portal then do this” statements throughout the code. For me, those lines were red flags that the code wasn’t clean and it was going to need some work.

Fixing that was no small task. Every other game item was a single independent object. Plus, I knew that I wanted to have other objects that could connect like a lever and a gate or a lever and a fan and the last thing I wanted to do was add a bunch more one-off if statements to handle all those special cases.

Player made connections in Orange

Player made connections in Orange

My solution was to break the portals down into single unconnected objects and to allow the player to make connections by “drawing” the connection from one portal to another portal. I really like the results, especially in a hand-drawn game, but man, did it cause headaches and break a poop ton of code in the process.

Connecting portals functionally was pretty easy, drawing the lines wasn’t too hard, but updating the lines when one portal is moved or saving and then loading that hand-drawn line… Big ugh!

But! It works.

AND!

The framework doesn’t just work for portals it works for any object. Simply change the number of allowed connections in the inspector for a given prefab and it works! Adding the lever and gate objects required ZERO extra code in the connection system! The fan? Yep. No problem. Piece of cake.

Simply. Fucking. Amazing.

Vertical Slice?

To be honest, I’ve never fully understood the idea of a vertical slice of a game. Maybe that was because my games were too complex and I never got there? I don’t know, but a couple of months ago, it clicked. I understood the idea and why you would make a vertical slice.

Then I heard someone else describe it… And I was back to not being so sure.

So here’s my definition. Maybe it’s right. Maybe it’s not. I’m not sure I actually care because what I did made sense to me, it worked and I’d do it again. To me, a vertical slice means getting all the systems working. Making them general. Making them ready to handle more content. Making them robust and flexible.

For Where’s My Lunch that meant getting the save and load system working, debugging the placement system, making the UI adapt to new game elements without manual work, implementing Steamworks, adding Steam workshop functionality, and a bunch of other bits that I’ve probably forgotten about.

To me, a vertical slice means I can add mechanics and features without breaking the game and those additions are handled gracefully and as automated as possible.

Adding Content

My to-Do List with game content towards the bottom

My to-Do List with game content towards the bottom

Maybe it’s surprising, but adding new mechanics is pretty low on my to-do list. As I start to reflect on this project as a whole, this may be one of the bigger things I’ve learned. About the only items lower are tasks such as finalizing the Steam Store, creating a trailer and adding trading cards. Things that rely on adding more content to the game.

So, with the “vertical slice” looking good, I quickly added several new game items that weren’t part of the game jam version. Speed zones, levers, gates, fans, spikes, and balloons with a handful more still on the to-do list. Each game item took two or three hours including the art, building the prefab, and writing the mechanics specific code. Each item gets added to the game by simply dropping in the prefab to a list on a game manager and making sure there is a corresponding value or type of an enum that is used to identify and handle the objects by other classes.

And that is so satisfying!

100% I will revisit and tweak these new objects, but they work! And they didn’t break anything when I added them.

Simply. Fucking. Amazing.

What’s Next?

Analog Level Planning

Analog Level Planning

The hardest part! Designing new levels.

The plan from here on out is to use the level designer that’s built into the game - that level that started as a sandbox playground.

To help make that process easier I’ve added box selection, copy and paste, (very) basic undo functionality, and a handful of other quality of life improvements. My hope is that players will be inspired to create and share levels and the easier those levels are to create the more levels they’ll create.

I also want to add enough levels to keep players busy for a good while. How long? I don’t know. It’s scary to think about how many levels I might need for an hour or two hours or five hours of gameplay…

While the framework is in place and gets more and more bug-free each day, there is still a lot of work to do and a lot that needs to be created.

Game Jam... Now What?

When you finish a game jam you’re exhausted, but hopefully you’re proud of what you’ve made. Or better yet proud of what you’ve learned.

And that’s what game jams should really be about. Learning something new. Pushing yourself to create new systems or learn a new technique. And we should celebrate what we’ve learned and the new thing that we created. This is so much more important than how well you may have done compared to others. 

GMTKJame.png

Certainly, measuring yourself against others has its place, I won’t say it doesn’t - I race bikes for fun, but that shouldn’t be your sole focus or measure of your success when taking part of a game jam. 

Which is great and all, but that’s not really what this is all about. I’m not here to give a pep talk. I want to talk about what to do with your game after the jam is over. Should it just gather digital dust never to be played again? Well, maybe. 

But! What if there’s more to learn? What if there’s more to do with that game?

AND THAT! 

That chance - that there’s more to learn and more to do is what this series of videos and blog posts is going to be all about. 

So let’s rewind a bit.

WML.png

This summer, for the Game Maker’s Toolkit game jam I made the game “Where’s my lunch?” It was an okay game. Nothing profoundly creative or groundbreaking - just okay.

And I like many others I planned on leaving the game in a folder and never really looking at it again. 

And then I got a suggestion from a viewer: Why not take that game and publish it? The process could make great video content and be a resource for others who might want to do more with their project. 

Whoa! 

I let the idea rattle around in my head for a few days - then a few weeks. The more I thought about it the more I liked it. 

Over the last year or two I’ve been far more focused on making video content rather than working on my own project. Which means I often just have a few hours a month to work on the game. The progress is slow AND that progress is further slowed by needing to remember what I was doing two weeks ago or what problem I was trying to solve last month. 

It’s not working great. And I suspect some of you know exactly what I’m talking about. It’s really really hard to find 10-20 hours a week to work on a project.

Now by their very nature game jam games are simple. Their scope is small - even tiny - and that makes it perfect for me, and maybe you.  

Game Jam to Steam (GJTS)

We can all dream… right? :)

We can all dream… right? :)

So maybe, just maybe… I can work on a game AND create decent tutorial content for the channel at the same time!

Now, this project isn’t going to make me piles of money - I don’t think that’s even a distance possibility and that’s really not the goal. The goal is to make something, finish that something...  AND! Document the process so that others, maybe you, might do the same thing with your game.

How many of us have dreamt about publishing a game to steam? How many of us have a game from a game jam sitting in a folder that with a few months of polish could be worth sharing with a larger audience? 

Now, I’m not talking about some generic 2D platformer with floaty jump mechanics that was your first Unity project. But I’m also not saying that you need to place in the top 10 of an international game jam. I certainly didn’t!

Out of 5381 games… Not too bad. Not Amazing.

Out of 5381 games… Not too bad. Not Amazing.

Maybe your game needs some redesign or a few tweaks to be it’s best and that’s okay.  “Where’s My Lunch” certainly does. It did well on fun factor and a few other bits but clearly isn’t a particularly original game idea. 

And again. 

That’s okay. 

So let’s do it. Let’s do it together. Let’s take a game from a game jam, polish it and publish it!

Videos Incoming!

For the videos, I’ll be trying to find the sweet spot somewhere between a traditional dev log and a tutorial. All while bringing you along for the ride, showing you my progress, and hopefully helping you make progress on your own project. 

FacePunch.png

I’ll be adding the game to steam (It already is! Just not public.), making use of Facepunch Steamworks, adding Steam features such as achievements, maybe the Steam Workshop, and of course, polishing and expanding the gameplay to add dozens of levels - all hopefully without too much feature creep. 

I’m also looking into several of the features offered by Unity such as analytics and cloud diagnostics...

When there’s a system or process that can be of use to the larger game development community, I’ll slow down and do more of a complete tutorial on how the system works and how I built my version of that system.

Sound interesting? Sound useful? I hope so. 

So Let Me Introduce You…

Okay, doesn’t show much… This is the sandbox level

Okay, doesn’t show much… This is the sandbox level

“Where’s My Lunch” is a hand drawn 2D game that presents a new puzzle to be solved by the player at each level. The goal is to steer the character towards their lunch --- but your controls aren’t very precise.

The theme for the game jam was “out of control” and that’s reflected in some of the chaos of the game play. Your only tools, in the current build, are bombs, portals, and gravity wells. 

The bombs explode and exert a force. 

The portals come in a linked pair and warp the player’s from one location to another.

And the gravity wells, they exert an attractive force based on distance from the player.

Now I WILL be adding to these as I work on the game, but the three mechanics were enough - or in reality it was all I could manage in a 48-hour game jam.

There are of course some bugs that need to get fixed or addressed. And mostly this has to do with placing items.  At the moment it’s easy to place a portal on top of the player and then be unable to move it later. I also need to add a “clear level” functionality to let the player wipe the level and start over with a fresh attempt.

Other things like placing a gravity well near the sandwich seems to make it too easy, but more importantly, some of these flaws allow a player to “break” a level by finding a trivial solution - which is okay, but it can take some of the challenge and thus reward out of the game.

Clever level design is maybe the toughest challenge that I see in completing the game. Puzzle games, I think, are often seen as “easy” to make but the reality is they just as tough or tougher than other genres… But again I need to remind myself that the goal here isn’t to make the most awesome game just to make a decent game.

Down the Rabbit Hole!

Let’s dig in a bit into how things actually work in the game - the mechanics of the game so to speak. 

mw3E5Y.png

Here it’s pretty simple, no surprise, and the game leans heavily on the physics engine - which does have downsides as it’s not fully deterministic - and by that, I mean that two identical starting conditions won’t have identical results - they’ll be close but not perfect.

But that’s a battle for another day, and the built-in physics engine is plenty good enough for my project.

The player object is a ragdoll with a basic bone structure built from 2D hinges. There’s not really any gameplay mechanics here, it’s just a lot more fun to watch the player fly across the screen with the arms and legs flopping all over the place. 

Player.png

Since the physics engine is non-deterministic, I chose to use a large circle collider on the player body as this made the motion of the object more repeatable with just a small loss in floppy ragdoll goodness.

After that, the code is mostly about triggers and a little custom code for each of the tiles or objects in the scene. 

As a fun challenge during the game jam and at the suggestion of a viewer, I added a sandbox level that allows the player to create their own level from scratch. This is one of the systems that I plan on expanding so that players can not only build levels but share those levels! Hopefully using the Steam Workshop functions.

Maybe I’ll even be able to incorporate some player-made levels in the final build…?

During the game jam, I quickly realized that I needed to streamline the workflow for making and saving levels. Having each level in its own scene was going to get messy in a hurry! I needed a better way.

One of the great things about game jams is you are forced to get creative and do so efficiently and as a result, I came up with a simple but effective scene creation system. 

SaveManager.png

My system, which I’ll do a full tutorial on, essentially scans the scene in the editor for game tiles which all have a “save level object” component and then stores the basic transform information for each object as well as a reference to what type of object it is. The data is stored in a list on a scriptable object. 

Since the data is stored in a simple list, I’m hoping this will make using 3rd party tools like Easy Save quick and hopefully relatively painless. The plan is to have each level stored in a separate save file which can, hopefully, be shared between players on the Steam Workshop. I’ve never done any work with the Steam Workshop, so I’m pretty excited about that!

And that’s pretty much it. There are certainly other chunks of code, such as the code that allows the player to wrap around the screen or to trace the path of the player, but those are small details and not core functionality. If you want to see those bits, let me know in the comments below. 

What’s Next?

Where is the game going? What’s going to be added?

ToDoList.png

I’ve got a list of new mechanics that I want to add to the game. These include buttons, levers, doors, flame throwers, ice, electric fields, and whatever else may come up. These mechanics should be easy to add and shouldn’t cause significant changes in the core architecture. 

There are things that WILL require significant changes such as steam integrations like achievements and the steam workshop. 

I’m also exploring the idea of adding more than one goal to the game - to give a bit more depth as the levels progress. So maybe it's not just about getting your sandwich, but maybe you need to grab a drink and chips on your way to your sandwich?

I don’t know exactly, but I do know that I need to build the code for that functionality pretty early in the project as this could affect quite a few other systems.

I’d also like to explore some sort of scoring system to add some replayability to each level. This might be the classic 3-star system or something more numeric on a leaderboard? I don’t know, but again this likely needs to get built sooner rather than later. 

If you want to see the full “road map” for “Where’s My Lunch?” check out the notion page. There’s a list of everything that I’ve planned out so far… in varying detail. It’s a living document and will get updated as the project moves forward.

More Thoughts

But! The real beauty of this project is not how much can be added, but how few major systems need to be created. The game is functional. It just needs to be polished and integrated with Steam.

That’s not to say this is a short or easy project. There is a TON of work to do, but it’s the amount of work and the type of work that is manageable and doable. 

So what do you say? Do you have a small game gathering dust? Why not polish that game and release it? Who cares if you make money? Simply publishing a game to steam is a huge accomplishment in and of itself!!

So go blow the dust off your game AND stay tuned to the channel as this project gets started. 




Strategy Pattern - Composition over Inheritance

The strategy pattern is a subtle pattern. It’s all about minimizing the duplication of code and decoupling classes. As an added bonus, the strategy pattern can also allow behaviors or algorithms to swapped at runtime without any messy switch statements or long chains of if statements. In the end it doesn’t have a super flashy or exciting outcome. It’s just good coding practice.

With some aspects of the pattern it’s easy to think, “Yeah, but this other way works…” But! The pattern is solid and avoids lots of little issues that can pop up later down the road when your project gets bigger.

Before we jump into the pattern lets first look at the problem it solves.

Inheritance Is Not Always Awesome

WeaponBase_Unpattern.png

Let’s imagine you’re making a game based around weapons, or at least has a lot of them in your game. It would seem reasonable to create a “Weapon Base” class that other weapons can inherit from. This base class can contain basic stats and functions that can be used or overridden by sub-classes.

For example, we may have a DoDamage function that gets called every time a weapon is used. The function might simply reduce the health of the player’s target.

This is all reasonable.

Going a step further, let's imagine that we want to create 3 fire-based weapons that will all inherit from the WeaponBase and on top of reducing the targets health will also do some actions specifically for fire damage.

FireDagger_Unpattern.png
FireSword_Unpattern.png
FireAxe_Unpattern.png

I now have 3 new classes that all have duplicated code. The DoDamage function has the same code from the base class, plus fire damage specific parts.  Updating the fire behavior means opening and changing the code in all the every fire weapon class in your project. This isn’t horrible with 3 weapons, but imagine having 20 or 50 or 100 weapons. Yeah, that’s not going to work.

I could also call base.DoDamage, but then all my weapons would be dependent on the base class DoDamage function, which is definitely NOT AWESOME.  If the base class function changes, all the inheriting classes change too and that’s not good. That’s not a solid foundation to build on. That’s a way to break your game in a hurry. This coupling between classes is what we want to reduce!

Now you might now argue that you could create a “Fire Weapon” class that inherits from the weapon base class and that all fire weapons inherit from… Which may work, but it is starting to get messy. Imagine now that you want to add ice or poision damage? You’d have to create Ice Weapon and Poison Weapon classes that those new weapons have to inherit from.

Okay, push comes to shove this might still be okay… Ugly, but okay, if the project stays small.

What if you now have a weapon that will do both fire and poison damage? Which class does it inherit from? Fire or Poison? Or do you make a combo class to inherit from? NO! Please don’t.

The strategy pattern can help solve these problems…

Strategy Pattern

The strategy pattern is all about encapsulating or wrapping up a behavior or algorithm in it’s own class. It’s also very closely related to the concept or belief that composition is better than inheritance! The exact details of how we do this are less important than the overall pattern so let’s start with a simple and common way to implement this pattern.

Interface.png

First, we create an interface called “IDoDamage” (you can argue all you want about using “I” to name an interface - I don’t care). This interface will have one function called “DoDamage.”

At this point, you might be thinking, “Okay, we’ll just implement the interface in all our weapons.” And that would be understandable, but it would be a mistake to do that as that would cause lots of duplicate code and not really buy us much in return from just good old inheritance.

WeaponBase_Pattern.png

Instead, we are going to create an instance variable of this interface in the Weapon_Base class. This class will also have a function that calls the DoDamage function on the IDoDamage variable.

Why? Good question. This is the crux of the whole pattern.

FireDamage.png

We can create classes that implement the IDoDamage interface. Each of these classes will have a different damage behavior. This will encapsulate the damage behavior AND make it so that we can change behavior at runtime by a simple assignment - no ugly switch statement or crazy chain of if statements needed.

For example, we can create a “FireDamage” class. This can do all the basic damage bits and most importantly it can then do any fire specific bits - maybe there are events that play sound effects or trigger specific lighting effects.

Then!

We create a new class for each weapon that inherits from Weapon_Base. Rather than hiding variables or overriding functions we use a constructor to set basic variable values AND to set the damageType variable.

FireDagger_Pattern.png
FireSword_Pattern.png
FireAxe_Pattern.png

While we now have a poop ton of classes, which could be a criticism of the pattern, we have very little duplicated code, and if we need to change the fire damage behavior, it only needs to be changed in one place in our project.

There is a neatness, a tidiness, a cleanliness that just feels good with this implementation. All we are doing is using a constructor to set up the weapon. The entirety of the damage algorithm or behavior is fully encapsulated in another class. While we are still using inheritance, we have decoupled much of our code, and much of the messiness of inheritance isn’t present in our solution.

Adding More Behaviors

The strategy pattern also works if you want to create other types of damage, such as IceDamage. To implement this style of attack, we need to create new IceDamage and IceSword classes.

IceDamage_Pattern.png
IceSword_Pattern.png
GenericSword_Pattern.png

Going Abstract

You could go either further and create generic weapons that have their damage and damage type set by a constructor. This could allow generic classes for each weapon type with all the data PLUS the behaviors injected into it.

Changing Behaviors

And I think the real cherry on top is that with the strategy pattern is that it allows easy changing of behaviors at runtime. Sure, you could do that with some if or switch statements. But those tend to be ugly. They break. They’re generally a brittle approach to programming and we can do better.

ChangeBehaviors.png

We can add a function to Weapon_Base to allow the damageType variable to be set. This would have the effect of changing behaviors. Something the code on the right.

Yes, I realize I made the variables public, but I don’t like changing values in classes from outside the class without using a function. If this was my project, I’d probably use private variables or maybe a public getter. 

With this functionality, a click of a button or the invoking of an event can change the weapon's damage type and thus much of it’s behavior.

If that’s not useful. I’m not sure what is.

Combining Behaviors

MultipleTypes.png

What if you really want that fire poison sword? Maybe your game is based around combining behaviors or abilities? Then what?

Make a list of IDoDamage values. The code can then iterate through the list and called DoDamage on each item in the list?

I’ll be honest I haven’t tried this but it seems solid and pretty useful.

Other Thoughts

The choice to use an interface in the strategy pattern is not the only choice. You may want to use an abstract class instead so that you can define variables. Personally I like the cleanliness of the interface and then simply injecting any needed data.

I also thought to use scriptable objects. And while I think that would work, I think it’s stretching SOs to a place they don’t fit particularly well. Writing the classes and then creating assets seemed like too many steps and I was struggling to find a situation where that would truly be better. But maybe I’m wrong?

I also wrestled with making the base class a MonoBehaviour or not. For simplicity I kept it as a MonoBehaviour so I could easily attach it to a button (for the video). I think that choice really depends on the use, but my gut say most the time I’d want it to NOT be a MonoBehaviour.



The State Pattern

Whoa. It’s been nearly a year since I’ve made a post. I’ve been busy. A lot has happened, but that’s a topic for another post.

So I’m going to try something new, well a few things. But the first thing I’m going to try is writing a blog post for my next video. I figure taking the time to explain the video in writing will help me cement the ideas and provide one more resource for you all. There are many people who’d prefer to read than to watch a video. So maybe it’s a win-win? We’ll see.

But enough of that. Let’s get onto the second new thing.

That’s is exploring programming patterns. It’s something I’ve wanted to do because I want to learn more about programming patterns. Plus Bolt 2 will eventually (!!) get released and when it does many of the basic programming patterns will be far easier to implement AND folks developing with Bolt can benefit from implementing them.

Since Bolt 2 is now fully in hiding under the protection of Unity (who knows when the alpha will make it out to the public again) the upcoming video will be entirely C# based.

I should also give credit where it’s due. I’m no genius - that should be clear if you’ve read more than a few paragraphs of my writing. Much of what I know or think I know about programming patters comes from the book “Game Programming Patterns” by Robert Nystrom. It’s well worth a look if you are unfamiliar with the topic of programming patterns..

The State Pattern

“Allow an object to alter its behavior when its internal state changes. The object will appear to change its state.”

Like any other pattern the State pattern has its limitations, but also like any other pattern when used correctly it can help to detangle code which can make debugging code or adding features easier and much less frustrating. And that’s a win no matter how you look at it.

You may have heard the term “Finite State Machine” or “FSM” thrown around. Both of these terms refer to the same thing which is an implementation of the state pattern. The Unity asset Playmaker is based on the uses of FSMs and Bolt has the ability to create them with “State Macros.”

To help illustrate the state pattern, I’ve created a simple Unity project. There is a NPC played by a capsule and it’s goal is to wander around the maze and collect the yellow cubes. When it sees a red sphere (critter) it will chase it and attack it. Nothing too fancy.

So with that in mind, how would you program this behavior? Take a minute and think it through. No cheating!

Just about ready to go up on steam! ;)

Just about ready to go up on steam! ;)

This actually doesn’t look too bade with the use of functions… but will get out of control in a hurry.

This actually doesn’t look too bade with the use of functions… but will get out of control in a hurry.

I know when I first got started with C# and Unity, I would have done it with an if statement or two (or seven). And that works. It really does. Until you need to add another behavior. Or another game mechanic gets layered in. And we all know it won’t end there. The layers will continue to get added until the code breaks, bugs appear or the project gets forgotten because it was getting too hard to work with.

Simple FSM = Enum + Switch

So let’s look at the simple FSM. I still remember learning about this and was utterly confused by how to implement it but at the same time amazed at what it did to my code once I finally got it working. At that time I hadn’t really learned to use functions well so I had 100’s of lines in my update function. Needless to say it was nearly impossible to debug and when I discovered FSMs it was a major break through!

Simple FSM using an ENum and a Switch

Simple FSM using an ENum and a Switch

In the case I described above the NPC behavior can be broken down into 3 different states or 3 different smaller behaviors. I thought of these as wander, collect and attack. A custom enum can then be created with these three values.

With the enum created a switch statement can be placed in the update function. For each case we can call the relevant function for that behavior. But we still need a way to change or switch (get it!) the state. For the most part this can still be done with basic if statements.

And now this may sound like we’ve back pedaled to our original solution and just made things more complex.

But!

There is a major advantage here!

When we started, inside the update function we had to have a way to determine which state we were in - picking from ALL the possible states. Imagine how complicated that would be if there were 5, 6 or maybe even 10 different states. Yuck! Nothing clean about that.

With this method we only have to decide IF we need to change states GIVEN that we are already in a particular state. This greatly simplifies the decision making albeit at the cost of a few extra lines of code.

In a FSM it’s common that a given state can only transition to a limited number of other states. For example in my case maybe I don’t want the NPC to stop collecting if it sees a red sphere and it should only attack a sphere if it’s wandering around with no cubes in sight. If that’s the case the “state pattern” may actually reduce the amount of code needed as well as serving to untangle the code.

This implementation of the state pattern can be used for all kinds of different behaviors. It could be used to control animations, background music, or which UI elements are being displayed. 

As an aside, in my personal project, I use a vaguely similar approach that makes use of a static enum and events for game modes so that various managers and UI elements can act or react based on the state of the game. The clarity of being in exactly one state has greatly simplified my code and made it far less error prone.

So this is all well and good, but you may be able to see the end result of this approach is still messy if the number of states starts to get large.

A Step Further => More Abstract + More Manageable

Having all the states switching inside the Update function can quickly get unmanagable and if nothing else is pretty hard to look at.

So let’s go one step further. This step adds another layer or two of abstraction to the system, still has some downsides but does clean up our code and will make larger FSMs easier to manage.

This step will place each state in its own (mostly) self contained class. The state will be in control of itself and will determine when to make a transition as well as determine which state to transition to.

Interface.png

Step 1 is to create a new interface. In my case I’ll call the interface INPCState. The interface will have just one function that will take in all the NPC data and will return a value of the type INPCState. This returned state will be the state for the next frame as the “Do Action” function will be called by the base class of the NPC which in turn will run the behavior for a given state.

The Wander State with all the functions included

The Wander State with all the functions included

Step 2 is to create a new class for each state of the FSM and that state needs to implement the interface INPCState. Each of these classes should also contain any functions or logic needed for that state. In my case I have choosen to leave all the variables on the NPC base class. This keeps each state class tidy, but does mean that the state class will be changing values on the NPC base class which is usually something I like to avoid - you win some and you lose some.

Inside each state’s “Do Action” function we need to call the relevant functions AND we need to decide which state to use for the next frame. You can see the full code to the left, but for now let’s jump back to the NPC base class which will help make sense of the return values.

Step 3 is to refactor the NPC base class. Here we need a new variable of the type INPCState that will hold a reference to the current state. We also need instances of each state - it would be possible to make this work with static classes and using an abstract class rather than an interface, but if you know what that means you can probably implement it yourself.

The simplified NPC Base Class

The simplified NPC Base Class

In the OnEnable function I’ve set the current state to the wander state to ensure that the current state variable is never null.

Then the real magic happens in the Update function. Here we have just one line! So awesome. Here we call the “do action” function on the current state and then set the current state to the value returned from that state.

That makes total sense, I swear it does, but it’s abstract.

Give a mintue to let it sink in.

This is so clean.

Step 4 is to add conditionals to the state classes to determine which state to be in for the next frame. Notice that we have passed in a reference to the NPC base class into the “Do Action” function and from there we can get a reference to the instances of the state classes.

Pro’s

The base class is exceptionally clean. You can now see how the class appears to change it’s state (behavior). Effectively the entire Update function changes depending on the current state and what in that state’s “Do Action” function. That’s cool.

If we want to add an additional state we simply create a new class, add an instance to the NPC base class and finally add conditions to allow a transition to the new state from other states.

As long as the number of states stays fairly small 5 or maybe 10 this is a pretty manageable solution.

Con’s

It’s hard to maintain if the system truly gets complex. In this case most sophicated structures such as behavior trees might be needed.

All the variables in the NPC base class are public. Which is a bit messy and not super awesome. This could be partially solved by creating a data container that itself is private in the NPC base class but has public variables… This passes the buck a bit, but would prevent those variable from being changed by classes without access to the data container. A generic data container would also potentially open the doors a bit wider for reuse of the states by other NPC types - so worth thinking about.

As mentioned before, the states are changing values of variables on the NPC base class. Not ideal and something I usually go out of my way to avoid if possible.

Introducing My Next Game (Video DevLog)

After my last game project was shelved, I started working on prototypes for a new game. Having learned the lessons of not just making prototypes but meshing those prototypes together early I built up the core mechanics of my next game over the span of a few weeks (just a few hours a week).

This was many times faster than my previous project.

I had the basics functioning and even better the prototypes were playing nice together. Seemly the next step was to starting building out content with, of course, lots of iterations of redesigning and refining.

As I made progress I could see that the amount of content that I needed to create could easily get overwhelming and potentially stick me back in a spot I didn’t want to be in. Designing and balancing content with little to no feedback seems like a poor choice and one that I want to avoid it if at all possible.

Learning from past mistakes, I knew that I needed to trim the game down. I needed to focus the game. I needed to get something playable and testable ASAP.

I’m looking at you my ugly ass combat system.

As I worked on the basic combat structures and mechanics I started to see that if the combat was refined it could do a lot for the game as a whole. If the combat is interesting and holds the players attention that would in some ways that take pressure off the other mechanics. Or more optimistically it could keep players engaged and maybe give the rest of the game time to mature as I build out content.

To take this one step further I saw that the combat alone could possibly make an entire game. Or at least a “mini game.” So I decided to take a horizontal slice of the game, just the combat, and do my best to polish and turn it into (potentially) a stand alone game. It seemed like a good idea and several months later it still does.

So enough typing, here’s my first DevLog video introducing the main idea of the game and the (very) rough prototype scenes.


Programming Challenges

Without doubt and maybe not for the better my focus has shifted from working on my game every night to trying to edit a video. Work on the game continues just slower than before… My fledgling YouTube channel continues to grow albeit at a limited pace. I’ve seemly snatched the “Bolt” niche on YouTube for the time being, but that’s a limited population and is likely to stay that way.

It’s time for something new.

With one part “hey this is cool” and one part “maybe this will expand my audience” I’ve launched Programming Challenges that can be completed in any programming environment or language used in Unity. This is something that I did with my students this year to help get over the significant learning curve of Bolt - and by most accounts it really helped. So why not bring it to a larger audience? If nothing else maybe it’ll help me refine my the challenges for my students.

The goal is to give short programming challenges that can be done in an evening or certainly without a huge time commitment over a weekend. The target audience is beginner to intermediate programmers and likely folks who are picking up Unity as a hobby and want to learn more.

But isn’t that what game jams are for?

For sure! But a lot of us can’t devote huge hours to a game jam on any sort of regular basis. And for those at the beginning of their game development journey creating an entire game (even in a month) can be intimidating.

Now I’m quite sure that there will never be the “perfect” challenge. Some will find a challenge far too hard or so easy that it’s not worth the time to fire up Unity. All the same this seems like a niche that is unfilled on the greater interwebs and continues the larger goal of giving back to the community that I learned from.

With that said, this last weekend, I launched the first challenge. The challenge is to create a dynamic grid of objects. It’s not a game and its not intended to be, but the programming used to “solve” this challenge is something that could easily be used in a game.

I’d love to hear feedback on the idea or this particular challenge. If you’ve got a suggestion for a challenge I want to hear that too.

The Bump From A "Viral" Post

Getting the word out about a game is tough. Really tough. Try as you might the world is a full of games with "great ideas." The social reach needed for a successful game launch is a huge hurdle for small teams and maybe more so for hobby or solo developers like myself.

Over the last week or so I've posted and shared a GIF and a video of a low poly waterfall. I created the scene to test particle effects for use in my second game. I spent a little extra time making it look nice as I wanted it to be a real prototype - could I actually make a half decent water fall?

Based on the response, the answer is yes, yes I can make a half decent water fall.

The Numbers

I first posted the waterfall on twitter. As of writing this the tweet has been re-tweeted 18 times and been liked 42 times. This seemly earned me 10-20 new followers and maybe a few more over the next several days as the tweet continued to get some attention. Not bad but not viral.

A post on the low poly reddits earned over 500 up votes. One or two people asked questions and I was able to share more info about the game. My website (this site) also saw a bump of about an extra 100 views. Not bad, but still not viral.

Then 10 days or so later I posted on Imgur, a site I mostly use to share images with online friends. I posted the GIF and saw 60-70 up votes before heading to bed. Nothing too exciting. When I woke up the image had over 1000 votes and was featured somewhere on the front page. Imgur classified it as a "most viral" image - at least for a few minutes. 

As I type this post the image has almost 1200 up votes and 290,000 views! Wow. 

So what?

Those votes and views trigger a dopamine rush, but what did they really do for me? How did they move my game forward?

I'll be honest I wasn't prepared. My game's landing page is pretty basic. I was updating a few bits as all the views and up votes were rolling in. I didn't link the game right away, and probably only the last third of the views had access to more info about my game.

Oops. Maybe a big oops!

So the best that I can tell here's my gains from the imgur post:

  • Twitter followers - nothing significant.
  • YouTube - 7 or 8 followers
  • Newsletter - 28 at last count
  • Discord - 8 or 9 
  • Website - 480 visits and 700 page views

These numbers are small... The Newsletter and Discord were the most exciting as both were essentially at zero before. I had "launched" the Discord server just a few days earlier with zero publicity and the newsletter gets almost no push from me.

While this activity felt good it's not the 1k, 10k or 100k people that I might need to launch a game "successfully," whatever that might mean. 

My Take Aways

I'm writing this post as much to share my experience as to organize my thoughts and what I learned in the process. For me this was a break through in the PR department, even if it's small. It helped me understand and get a feel for what success could look like. 

The value of a good image is worth so much. Sharing works in progress have their place, but maybe not with the general public. People say share and share often and don't wait until the game is finished to share your work. I think this is largely true, but I also think there is something to be said for taking a little extra time to polish what you are going to share. Just because you're excited doesn't mean that very many other people will be too.

Where's the balance? I'm not sure, but I have a better feel for it now after this experience.

Motion adds so much. I've read this over and over, but I'm not sure I really understood. I also shared an image of my river at the same time as the waterfall. The river has motion but it's much more subtle - it got almost no response! At this point I question sharing much of anything unless there is some form of motion. All of our social feeds are full of static images - some are amazing, but the images that have motion are so much more engaging.

Somehow I need to reproduce this "viral" post over and over! It's scary to think what it would take to get to the social reach needed for a "successful" game....

 

 

Resources: Processing, Consumption and Inventory

As a solo developer (of an admittedly over scoped game) relying on outside assets is a key to building a game "quickly" and efficiently. I'm not the type of person to subscribe to the idea that I need to build everything from scratch. I have no desire to build my own game engine, but I do understand why folks often prefer to roll their own solution.

I've become very skeptical of assets that run with the game. I have learned that editor tools are more reliable and don't come with performance downsides that many runtime assets do. I've tried using several assets that are overly bloated or have turned out to have poor performance. My snow shader and graphing tool came out of such experiences. It's a tricky to find the balance between using pre-made tools and rolling your own. There are pro's and con's both ways.

Game #2 will allow players to collect and use items - this will in fact be a key mechanic. This means that I need some kind of inventory solution. I did a little research on how to do the basics, but decided to also look at solutions on the Unity Asset Store. If nothing else the Asset Store can be a good source of ideas. 

As a Unity Plus subscriber I get discounts on a handful of assets. One of those assets is Inventory Pro. So I figured it was worth a look since I was shopping for a inventory solution and the reviews were nearly flawless. 

I watched the tutorials and did as much research as I could. While not "cheap" it's an asset that would take me several days if not weeks to reproduce even in the most basic of forms. Plus it has a level of polish that would take even more work on my part.  So why not give it a shot?

I made the purchase and spent some time playing around. My first impression was positive. It has a nice and easy to use editor. Out of the box it handles person inventory, vendors, looting, banks, a skill bar and two styles of crafting. It comes with a pretty decent default look too (but, I suspect almost any developer will want to modify it). What's not to like about it?

Inventory Pro Editor - Item Editor

Inventory Pro also plays nice with several other popular third party add-ons. This includes Playmaker for those who don't want to dink around in C#. 

It also has custom functions for Behavior Designer which is a major plus in my book as I intend to use Behavior Designer as my AI engine. 

If you are intending on building game with a fairly typical or standard use of inventory then Inventory Pro should be on your short list of assets to check out. However, if your design has some non-standard uses you should keep reading. 

The Other Side of the Coin

As I continued to explore and think more about the custom needs my game was going to have I was becoming discouraged. The code base is all open source, which is greatly appreciated, but it feels like a mess of inherited classes and prefabs. Ugh. The documentation is decent, but doesn't do a great job of describing how to truly customize the tools. The learning curve is moderately steep.

The odd blog post by the developer were very helpful and cut hours out of my work. The needed info is out there, but it can be a little hard to find. 

When trying to setup a scene you can't simply drag and drop UI prefabs in the scene. They don't easily slide into a scene because there are too many connections that need to be made. Too many prefabs that need to be dropped into the inspector or combination of components that are required. It's certainly possible, but it's not easy.  Adding the UI to a scene is best done by copying from a demo scene and then turning off the parts you don't need - a custom editor to add the parts you want and get them all connected correctly would be a major plus and make the product that much more user friendly. 

There is a cost to using someone else's code base... That shouldn't be a real surprise. I got frustrated enough with Inventory Pro that I spent a few hours working to roll my own custom inventory code. It was all going well until I began to write a custom editor to create content. I went running back to Inventory Pro and I'm very glad I did.

Custom Windows

I mentioned a chicken, so why not include a image of my chicken?

For Game #2 I need some custom windows for resource consumers and resource processors. A resource consumer could be something such as a steam engine from my previous post that may take in wood or coal and produce a more usable form of energy.  While resource processors may be something such as a windmill that will process corn into corn meal that can be used to feed your chickens, i.e. turn items into other items.

Each of these custom windows is easy enough to create from a purely UI perspective, but coding them took a bit more especially as I was to digging through someone else's code. 

A resource consumer is very similar to a vendor in that individual objects in a scene will have there own collection that is loaded into a common UI. The main differences being that the resource consumer needs to do something with the items even when the player is not currently using that object, i.e. a steam engine should continue to burn coal and produce energy when the player is busy elsewhere and I don't want to be selling coal to a steam engine...

A snippet of the some of the custom code - All in all there's several hundred lines in the new classes some is copied other bits are mine

Rather than inherit from the vendor classes, which would bring functionality I didn't want, I chose to essentially copy the vendor scripts (ItemCollection and Trigger) and modify the scripts once I had basic functionality working.  The result was a custom trigger script, custom UI window (damned ugly at the moment), a custom collection script that controls what is shown in the UI as well as a base class resource consumer that is designed to be extended for a variety of resource consumer objects (steam engine, chicken feeder, etc). 

I promise it won't be this ugly in a final build

The resource processor is a bit different. At its core resource processing is very similar to crafting. Items go in and products come out - all following a blueprint. Given that Inventory Pro has a built in crafting system it seemed worth the time to fight through the code to create a custom "crafting" window that would meet my design needs. 

The idea here is a that a player (or NPC) drops off some items to be processed and it gets turned into a different item that can later be collected. This means that the UI needs to have an input and a output collection/inventory. It's also required that each individual scene object has it's own input and output collections to that get loaded to the UI when the player interacts with the object. A final two requirements is that the resource processor continues to work when the UI is closed and that the products get assigned to the correct scene object when the processing is done so the product doesn't get lost and the player can collect it later.

A snippet of the Custom Trigger

This last requirement was the biggest hurdles and required about an hour of hunting through code to follow the flow of the information. Inventory Pro has a "craft info" class that contains all the basic information which gets passed through about 8 different methods before an new inventory object is actually created.

I almost lost it at this point. Lots of deep breaths needed. 

To get it all working required an addition to the CraftInfo class to track what object had ordered the product to be created. This allows a finished product to look up where it was supposed to go and assign it to the appropriate collection. 

Custom Inventory Items

Default Item Types - Plus 3 of My own

While I found the process of adding custom windows and functionality challenging and frustrating, adding custom inventory item types was easy and almost fun. Out of the box Inventory Pro comes with several default item types, but anything beyond the typical RPG will likely require custom item types.

Different types have different properties (oh, shocking). These properties are not particularly well documented or at least I haven't found the documentation. Thankfully most are self explanatory. 

Game #2 is not the typical RPG with the collection, crafting or upgrading of gear playing a central role. Rather most inventory will have some use in creating something in the world. This might be a shovel that is used to prepare the ground to plant a crop or coal that will be used by a steam engine to power an industrial building. Inventory Pro's items all inherit from a parent class that calls a Use() function. This function can easily be overridden to perform any actions needed. The Use() function is called when the player uses the object. Which can be done from inside the inventory or from the skill bar.

A sample custom USE() function for a tool item type.

The Use() function returns an integer that indicates whether the object can be used.

In the case shown using the tool will call an outside public function that toggles a mode of the game (i.e. use a shovel and you can dig to plant seeds). 

The inventory item can also have public variables that will be displayed in the Inventory Pro editor. For example the Tool Type enum can be set for each inventory item of this type inside the editor which makes for easy and organized content creation. 

The ease of creating custom inventory items was a stark contrast to making custom windows and triggers. Why can't the rest be this easy?

The Final Verdict - Inventory Pro

Inventory Pro caused me a good amount frustration, plenty of swearing but also gave me a much more functional inventory system than I could have created on my own.

If you are looking to build a game with non-standard use of inventory and aren't comfortable with C# then you should probably look else where or be willing to hire a programmer to code up some custom solutions. 

But if you don't need custom functionality or if you are comfortable with C# and reading someone else's code then Inventory Pro can solve your inventory needs far quicker than you'll be able to roll your own solution. Mucking around with the custom windows wasn't particularly fun, but the end product was worth the time and money.

Energy is Everything

Game #2's design is fairly well established in my head and on paper, but I'm still very much in the stage of exploring what I can reasonably do from a technical perspective - not to mention from a time perspective. (Read as: I'm trimming down the scope by figuring out what I can or can't do.) I'm running through the big picture list of features to make sure that each can be implemented in a way that I like and fits the vision for the game. This is an iterative process. As features are implemented other aspects of the game are getting adjusted or redesigned, but that's not exactly news worthy...

Energy

A core feature/game mechanic of Game #2 is going to be energy. Energy is everything. With more energy we become more productive. With more efficient use of energy we can do more with less. The use of energy is what allows for modern society to function and, to hint at a game mechanic, use of more energy allows for a higher standard of living. 

There's of course a dark side to energy consumption.Increases in efficiency allows more to be produced with less. That might be less workers, less energy or less effort. All of which improve the quality of life. While this can drive down prices, increase production and consumption it also has the effect of higher unemployment or underemployment - i.e. the current stat of the rust belt. 

A rigged and animated steam engine model. This was also the first animation I'd ever rendered in Blender - GIF made with GIMP.

This give and take concept is something I very much want to explore in Game #2. The first step of which means I need to develop an energy mechanic. The mechanic requires the "generation" of energy (the physics teacher in me cringes writing that), the distribution of the energy, and the "consumption" of that energy.

The game is likely to be set in the industrial revolution time period. So... Steam engines!

Steam engines can provide a local source of energy. They can be fed with wood, charcoal or coal - really anything that'll burn. All of which can be found or produced easily with low tech methods. Steam engines can be built on site in a variety of sizes. Seems like a win. So off to Blender I went to see if I could produce something that I liked. 

A view of the rig in Blender.

Nothing profound in the modeling department, but rigging and animating is still pretty new to me. I didn't want to "fudge" the animation I wanted a rig that with the rotation of a single object could animated the entire model.  I wanted this for ease of animation as well as for a degree of realism. 

A combination of bones and constraints to tie the mechanism together and allow smooth animation. The constraints of copying location, rotation and or scale were all new to me and opened my eyes to a new world of possibilities. I'm excited to play with more mechanical animations...

There are very few tutorials on mechanical rigging - I might put one together in the future. Who knows?

I'd like to work renewable or at least pollution free energy sources into the game as well. At first glance windmills are a pretty obvious choice - so those will be added at some time in the future. At the moment I've avoided rivers (as I have no idea how to make a good looking low poly river) so water power is more or less out for the moment.  

Energy Transfer

Power Lines - Mostly eye candy at the moment

Power Lines - Mostly eye candy at the moment

The industrial revolution largely used mechanical energy which (clearly) has limitations. Moving towards electrical power as a way to transfer energy could help in several design areas, but could break the immersion or at least a sense of believably.

While it may not fit with the (current) intended time period I spent a little time playing around with power lines. Being able to generate power in a centralized location could lead to higher efficiency and more contained pollution. This is further specialization would allow workers (and the player) to spend more time doing something besides feeding fuel into a steam engine. 

Borrowed Code that when passed an Array of Points with Return a larger but smoother array of points - Don't Remember the Source, Oops.

I can see the game going away from a historically accurate time period (ha, as if I'm capable of historical accuracy), but I don't want to delve to far in to fantasy or steampunk styles either... 

The power poles are just to cubes scaled to look like modern poles. The lines are line renderers that start with three points and then are smoothed by some (borrowed) code to add additional points. 

The performance of moving the poles is pretty bad and will need some optimization if the code makes it into a build. I have to redraw all the lines when a pole moves - at the moment EVERY line is redrawn.

To be honest the power lines came out of frustration (lack of creativity) with another idea. They may just be a short lived idea that goes away.

Some form of energy transfer mechanic will need to make it into the game whether that is power lines or not I have decided. At the moment the energy transfer mechanic is simply the player or hired workers stoking the fires of steam engines - I think a step up in sophistication would be good.

Plenty more to iterate on...

Graphing Script - It's not exciting, but it needed to be made

A download link to my graphing asset is at the bottom of the post - if you want to try it out.

Game #2 will likely be centered around economics as well as climate (change). Deciding where to build a farm will likely be best done when looking at some climate data. Does it rain enough? Maybe too much? How hot does it get? Is the ground water polluted? Or looking at historical prices of commodities may help a player decide what type of business to pursue or how much they can afford to pay NPC employees. I don't want the game to be a data crunch fest, but data will be a part of the game. So naturally I'll be needing a way to visualize that data and graphs seem like a good way to do that. Pretty sure players don't want to read a list of float values.

Visualization - Basic line (scatter) graph

Graph Maker

I'd seen Graph Maker on the Unity Asset store and bookmarked it many months back. The reviews are pretty decent and it is definitely capable of a lot of heavy lifting. I'm aware of at least one reasonably successful game that has made use of it. So it seemed worth the risk of a few bucks. Graph maker clearly has had hundreds of hours poured into it. It's polished and feature rich.

All those features have also caused it to be fairly complicated. Each graph has several nested prefab elements each with scripts attached. The documentation is also a bit rough. As a new user the number one thing I want to know how to do is send the graph a list or array of my data and have it graph it.That's it. One simple function. So where is it?

I spent a while clicking around trying to figure out where the data was stored (turns out to be in the series prefab/script). I opened the documentation and couldn't find clear directions of how to send my data to the graph via script. I opened the scripts in search of the list or function that would import my data... Couldn't find what I was looking for.

There is a neat reflection script that can be attached to gameObjects and looks like it could do some handy stuff, but I couldn't get it to do what I wanted. All in all the asset looked way bigger than what I needed. Do I need radial graphs? I don't think so... 

The second thing I want to do is modify the appearance of the graph. The shear number of (nested) prefabs not to mention the number of settings in the main script it seemed like it was going to be a long battle to customize the looks of a graph.

So as I so often do, when I can't figure out an asset I start down the path of rolling my own asset. If you have more patience than I do, I know that Graph Maker is a good asset and will make pretty graphs for you. 

Rolling My Own

The goal of rolling my own graphing asset was to make something simple, lightweight and easy to use. As of writing this post my graphing asset has 6 prefabs and three scripts (one of which is a custom inspector to allow graph updates in edit mode - another detects mouse hovering). The prefabs largely consist of gameObjects with just an image component. A few such as "tick marks" or "axis labels" have children with Text components, but nothing gets more complex than that. Sending data to the graph is done with 1 of 3 functions. Pretty simple. 

Just send the data and let the graph do the rest.

In the end it's taken me way longer to roll my own graphing script then it would have taken to figure out Graph Maker. Is mine as pretty? No. Does mine do nice tweening animations? No. But I know how mine works and I know how to modify mine if I need to.

The feature list is short. It can switch between line (scatter) and bar graphs. The axes, points, connecting lines, and tick marks can all be tweaked in size and color. 

Bar graph of the same data as at the top of the post

Fonts, font size and font colors are all of course adjustable as well. Modification of the images was left out of the inspector/script and can be done with the prefabs. This was done for simplicity and the simple fact that changing images is less of a "tweak" than font size might be. 

I still have one feature to figure out and that's auto-scaling. Currently the axes will auto scale and adjust to fit the data, but the values displayed on the axes does not. I'd like to figure out some basic auto scaling to keep things simple - sure I can manually adjust the values in the inspector (or by script if I expose the variables or add a new function), but that's hard to do when the game is published... I like to be involved the community, but manually adjusting each player's graphs is a bit much. I'll keep the linked package up to date if anyone has ideas of how to auto scale I'd love to hear them.

Edit: The auto scaling is now working. 

Download (Free)

I may polish the asset a bit more and put it on the Unity Asset store, but that's a lot of work for not much of a return. Until then I'll happily handout a free download (box via goo.gl). Feel free to use it or modify it. Just don't flip it and sell it - don't steal my $12 in potential sales! If you do use it I'd love to hear about bugs or ways to improve it (but not bloat it). 

Not until writing this post did I realize I named my asset the same as the one I'd purchased. Oops.

Environmental Simulation Part 1

When I settled on the current game design idea a central piece was an environment simulation that would effect player experiences and that player choices could in turn effect - creating a feedback cycle.

Iteration 737 - Humidity Heat Map

The goal wasn't (and still isn't) to create an environmental simulation that was "physically accurate." The goal was to create a simulation that was an abstraction of reality or at least had some of the key features seen day to day and year to year. I wanted the player to be able to alter the world around them in a way that reflects reality but that doesn't need to be 100% realistic. 

Key Features:

  • Day to day temperature swings
  • Seasonal temperature swings
  • Wind to transport moisture
  • Water/Rain cycle
  • CO2 effects
  • Pollution accumulation and transport
  • Runs off the main thread

Building Blocks

The first step in creating the simulation was to break up the environment into a series of blocks. Each box would have it's own set of environmental variables (temperature, humidity, ground water, wind, etc). These "climate blocks" would interact with it's neighbors to create localized weather and also to allow local variances such as terrain height and cloud density to impact the weather. 

Test Terrain with Climate Blocks

As the simulation developed and more complex interactions were add a few changes/additions to the climate blocks were needed. The first critical piece was the addition of an "atmosphere block" on top of each climate block. The atmosphere block is simulated air space above that often has a different temperature than the air on the ground/ocean. This allowed for up and down drafts that could help move clouds and cause an on or off shore wind depending on the season (more about this later).  Without an onshore wind clouds and more importantly rain rarely make it to the land.

A second key addition was the classification of terrain types. At the time of writing this the simulation is only using three types of terrain ocean, grassland and mountains. This largely controls the "target" temperature of climate block and in the case of the ocean maintains a constant saturation of ground water. Oceans have moderate target temps with smaller seasonal and daily fluctuations. Grasslands have a higher target temp than the mountains but both have larger daily and seasonal fluctuations than the ocean.

Daily and Seasonal Temperatures

Seasonal sun intensity is controlled by an animation curve that is sinusoidal in shape. Max values occurring during the "summer" and of course minimum values occurring during the "winter." A second curve was used for daily fluctuations. The curves are currently identical... That may change in the future. 

At first these curves were used and tuned to be a true energy flux with energy being added during the day and energy lost during the night. While more physically accurate and potentially allowing for more emergent weather, it also made it far more difficult to tune and balance. After significant testing and tuning this method was abandoned for a more controlled method. 

Each terrain type has a median temperature that serves as a target temperature. There are also values for seasonal and daily fluctuations of that temperature.  This means that median temperatures + seasonal flux + daily flux is roughly the high temp and likewise median temperature - seasonal flux - daily flux is roughly the low temp. Variance from this is caused by the connection of neighbors and other factors. 

One of the other factors that adds some variability is the average height of the terrain. In the real world the higher the terrain the cooler the air. To reflect this each climate block samples the terrain height at multiple points and calculates an average height. From this the median temperature is adjusted slightly. This provides variation in the climate that (hopefully) lends itself to more interesting and emergent weather.

Wind

Wind in the simulation does not  have a physical presence and is simply a Vector3 that stores the wind velocity. The wind for an individual climate block is calculated based on the temperatures of the neighboring climate blocks, including the upper atmosphere. The inclusion of the upper atmosphere allows up and down drafts which allows for onshore or offshore breezes (as mentioned above). 

To calculate the wind the simulation calculates a temperature difference between the climate block and a neighbor and then multiplies that by a vector that goes from the climate block to the neighbor. Final direction (sign) of the wind is based on blowing from hot to cold. 

The simulation sums all the winds due to neighbors to arrive at a (nearly) final wind value.

A prevailing wind is then added. This allows larger global winds to be added to create larger and different weather patterns. The strength of the prevailing wind is a tune-able variable. Current testing is with an in/out pattern that helps to blow clouds away from land in the summer. 

An early WEather Prototype

After the prevailing wind is added the vector is normalized. There was some debate about normalizing the wind...  In the end the choice was made to keep the normalization as this meant that clouds always would have some wind. It also prevents unrealistically large or small winds that become problematic when trying to transport clouds/moisture.

The final step is a check on the vertical component of the wind. Since the upper atmosphere is often at a very different temperature it can therefore be the dominant contribution to the wind. This is a problem due to only simulating two layers of atmosphere rather than more layers or the ideal of a continuous atmosphere. Effectively the vertical component is clamped to a range between -0.5 and 0.5. This helps to keep clouds generally moving horizontally.

Additional controls are needed to avoid the clouds going too high or going through the ground. The altitude of the clouds is mostly visual as the horizontal location determines where clouds can deliver rain. Because of the this a simple min and max altitude are set. Clouds check against these values and degrees of freedom are restricted in the rigidbody to prevent clouds from going outside the bounds. Checks on vertical velocity are also necessary to allow the clouds to move away from the limits. 

Continued in Part 2

In Part 2 I'll discuss the most difficult part (so far) of the simulation that being the Water and Rain Cycle. Or more specifically the balancing of that cycle.

The Inevitable : FTF PostMortem

Fracture the Flag
Fracture the Flag

Fracture the Flag is my first and only game. Not the only game that I've published. It's my only game, period.

I'm pretty damn proud of FTF. Sure I had dreams of selling 100k copies or 50k copies or even 10k copies. None of which happened, but the real goal was to learn, to build a (small) community and create a game that at least some people thought wasn't total garbage.

By that measure it has been a complete and total success.

While the code base is a mess of poorly written spaghetti code it mostly works. I learned how to better organize my code and how to create more efficient code. I discovered that multiplayer is great idea, but like so many before me, I also learned it's freaking hard to implement. What works well on two test machines on my desk is very different from two players that are on opposite sides of the Atlantic. I figured out a basic workflow from Blender to Unity. I stumbled through the process of creating basic editor extensions to make my game development a little easier. I also learned I had no idea how to set up the lighting in a scene and still don't.

I learned that there is plenty more to learn.

Managing the game and community surrounding the game after the initial Early Access release was stressful, but still more rewarding than I could have expected. I had no idea how buggy the game was. Not really. I had no idea how thoughtful and kind some people would be. So many people were constantly giving feedback and helping make the product better. My biggest lesson in taking a game from Greenlight to Early Access through to Full Release is simple:

Be open. Be honest. Be human.

Folks can smell from miles away a developer that just wants a quick paycheck. While not every interaction in the FTF Steam community was positive I found most can be turned that direction with a little humility and honest listening. Not every customer has a good idea or even a valid complaint, but most do. So I did  my best to listen.

Case and point: Two friends each bought a copy of FTF hoping to play together. They quickly found several game breaking bugs that earlier players had simply ignored or hadn't noticed. These two players proceeded to rip FTF to shreds on Steam reviews - yes plural, they each wrote one. Both brutal and brutally honest. I didn't respond to the review, but when they posted in the forums I took the opportunity to start a conversation. After the exchange of several comments I had great feedback from the players and removed several sizable bugs from the code base. They dropped their negative reviews and decided not to ask for refunds. I never saw if they left positive reviews, but the huge negative reviews were gone. That's a huge win for a solo developer and worth every ounce of effort.

Fracture the Flag
Fracture the Flag

Let's talking pricing.

When I first had a vision for FTF I thought surely the game must be worth $10-12. I mean I've worked so hard on it! It's got multiplayer for crying out loud. As it got closer to the Early Access release date I got a bit gun-shy. I refocused on my main goals. Making money would be nice, but it wasn't the primary goal. So I cut the price. I cut it a lot. Down to $2.99 in the US market. This seemly had the effect of lowering expectations and doing so in a helpful way.

The early reviews were incredibly positive. Early on FTF has a 90+ percent positive rating - and not from people who got free keys. The game sold reasonably well in its first week with sales continuing to trickle in as the weeks passed.

ftfsteamreviews
ftfsteamreviews

I fixed bugs and added features before the full release. I added so much! So many good ideas came pouring in from the community. So I decided to raise the price. To the price of a latte in Aspen... All of $4.99. Sales slowed and expectations seemed to rise while the rating on Steam dropped to what it is now, 78%. Was it a mistake?

Then came release day.

Sales were modest but better than I hoped. The first day as a full release saw almost no exposure on Steam but was still the best sales day in the short history of FTF. More copies of FTF were sold in the those first three days then in the entire first week of Early Access. Not too shabby.

I hear people say you only get one release. Maybe that's true. But I think building a community and getting positive reviews helped to serve up more sales then FTF would have seen had it jumped straight in as a full release. I know I'm more likely to buy a game that has decent reviews and has been "out" for at least a little while. But who really knows, maybe I'm just seeing what I want to see.

7 months after the initial Early Access release FTF is essentially "finished." No, it doesn't have every possible feature. Yes, there are still bugs. And no, I didn't make enough to quit my day job - not even close. Sales are generally within the margin of error shown by Steam Spy but I have often seen the numbers dip too low (but I've never seen them go too high). I made enough to easily pay for a high-end mountain bike and new set of skis and boots. For a guy who's day job requires bikes and skis... Not a bad result.

My hourly wage? Probably didn't make it to minimum wage... No, let me rephrase that. I didn't make minimum wage.

You can see sales spike on the release day and then again during sales and of course the day FTF came out of Early Access.

sales-graph
sales-graph

So now the game is in the long tail. Sales have slowed as expected, but the trickle is still going. At least enough to buy my wife and I dinner out once a week.

So what would I do different?

No multiplayer. While I nearly dipped my toes into that pond again for game #2, a quick read of some FTF comments reminded me of the horrors of trying to sell a multiplayer game as a solo developer. This might be a lesson I have to learn more than once...

For game #2 I want to find an outlet for early builds beyond Early Access. Find a smaller market. Find a community interested in giving feedback and more willing to take risks on a title. Take the time to polish the game before heading to Steam.

As a solo developer I need my games to be more procedural. With FTF building a level took days and the way I built the level meant I often couldn't even make small changes without completely scrapping the level and starting over. Got a rock in the wrong spot? Combined the wrong meshes and can't get good occlusion culling? Too bad.

Game #2 needs to be a game I want to play. FTF started as memories of playing Crossbows and Catapults a kid. I loved that game. Then FTF started to morph. It turned into something totally different. Sometimes for good reasons and sometimes not. It's not even close to the game I first set out to make. As a result I tried to squeeze into an already defined genre and all the expectations that came with it. Slowly, with each added feature FTF became a game I wasn't really interested in. So, now I dream of the game that I simply want to keep working on. Wouldn't that be magical?

What's next?

Game #2 is next. I have a vision, but not a complete plan. I want to create something different. (Shocking I know). I am fascinated by how poorly we treat each other as humans and how poorly we treat our beautiful planet. I dream of a game that could explore those very real issues while still being fun and challenging. In my head the game is so hopelessly over scoped I worry I may never be able to finish it or if I do it will turn to total shit.

So ignoring common sense, step one is to create a game world that I want to spend more time in...

Procedural Trees 1
Procedural Trees 1

I know that's ass backwards for most folk, but a world that is pleasant and enjoyable to walk around it seems like the first step in learning to appreciate that world.

The page has just begun to be built, but you can see what there is to see about #2 here.