Spectragate




Fixing common Advanced C# Messenger issues

Category : Tutorials, Unity · (1) Comment · by Oct 12th, 2015

In the latest project I’m working on I’m making heavy use of the Advanced C# Messenger. It’s a brilliant script that acts more like a Mediator Pattern than a plain Send/Receive messenger, which is fine with me.

However as great as this plugin is, there are two small issues I ran into pretty quickly.

No Listeners Available

To make ACM (is that an acronym?) work like a true mediator system, it needs to give exactly zero craps about what’s actually listening to the broadcasts. Unfortunately if you try to send of a broadcast and no listeners are setup, you’ll quickly run into this error:

“BroadcastException: Broadcasting message “SaySomething” but no listener found. Try marking message with Messenger.MarkAsPermanent”.

Marking the message as permanent wont solve anything. Luckily ACM comes with a way to fix this: comment out this line at the top of Messenger.cs

This simply disables the check for any listeners before it broadcasts a message. Easy! The documentation on the wikipedia page doesn’t mention it, so unless you connect the dots yourself you’ll go down the wrong path thinking there is an issue with permanent messages, like I did.

Unexpected results when restarting scene in Unity 5.2

This one took me a bit longer to hunt down. You load your scene by pressing the play button in the Unity Editor (so no Application.LoadLevel calls are made) and everything loads and works fine. You then call “Application.LoadLevel” to restart your scene and, no matter how simple your scene is, some messages make it through and others don’t. What the horse?

This bug is because of a breaking change in Unity 5.2: Before Unity 5.2 OnLevelWasLoaded was called before Awake. Now that this has been fixed, any listener events you are setting up in your Awake calls are going to get deleted when OnLevelWasLoaded is called. This is because Messenger.cs automatically calls ‘Clear()’ (which removes all the current listeners) when this event triggers.

The simple fix is to comment out the .Clear (line 304 in Messenger.cs) that happens and call it manually yourself when you are changing scenes.

Unfortunately because OnLevelWasLoaded no longer fires before Awake, there doesn’t seem to be a replacement method yet that can take its place. Perhaps a new OnLevelWasUnloaded method would be a handy?

Solving gaps between scrolling background sprites

Category : Tutorials, Unity · (1) Comment · by Oct 4th, 2015

Note: The background sprites in this blog post were downloaded from opengameart: Forest Background by ansimuz

In the game that I’m currently working on I need an infinite scrolling parallax background behind the player. Because the camera needs to be orthagraphic but support parallax scrolling, I decided to make the world move while the player stands still. Everything was going great until I noticed this:

gap1

I had a damn gap appearing between my tiles – and it wasn’t all the tiles, in fact my foreground seemed to work ok. It seemed to happen more often with very slow moving sprites. After much research I realized that the problem was occurring because of float precision errors in Unity. Basically this coordinate:

gap2

would move a few frames and then explode into something like this:

gap3

The tile at the front of the queue that’s moving ends up with .4599998, but it still has to render to a single pixel on the screen. The camera has to take a guess how to render this and either rounds the position up or down, placing the sprite one pixel too far or short, creating a gap between the tiles. In many 2D only game frameworks you don’t notice this issue because the world unit to pixel ratio is already 1:1, so it’s easier to move around consistently.

My first solution was to round all coordinates down to 3 decimal places – it seemed like an easy fix. However, the gap started to appear again and I realized that I was just now doing in code what the camera was doing when it rendered anyway – taking a precision error and then trying to guess if it should be rounded up or down.

After 3 days of faffing about with different techniques I came up with this solution:

My orthographic camera has a ratio of 1 Unity world unit to 100 pixels (note: You can find more about getting your orthographic scale here). What I realized was that for a sprite to move a single pixel on the screen the absolute minimum distance it can travel in Unity is 0.01 world units. As long as I constrained my background movement to move only in multiples of 0.01 I would avoid any rounding or float precision errors. After all, if something lands in 10.672, how does the camera reliably render that at .672 of a pixel?

I changed my movement code to simply use 0.01 as the minimum distance a sprite can travel, which seemed to work great except for one tiny issue:

gottagofast

It’s way too fast! He’s supposed to be running but not that quick! The problem now is that 0.01 as a minimum distance isn’t small enough. If the backgrounds move that 1 pixel every frame, that’s still 60 pixels being covered every second. The solution was to take the movement code and place it into a Coroutine that runs at different intervals for different layers. For the background, they only shift one pixel every 0.05 seconds, while the foreground moves every 0.03 seconds.

Very simple but very effective. One drawback with this technique (which is less to do with the technique and just pixel based movement) is that you can’t move the sprites with anything that uses floats as its values – this includes transform.Translate, moving using a velocity or multiplying movement by delta time.

If you need pixel based movement in Unity, make sure you are only moving in whole pixel amounts based on your orthographic camera size.

Some final notes

If you find that the pixel based movement for very slow backgrounds is too jerky, you can get sub-pixel movement by setting the move distance to half your orthographic camera size (eg. 0.005 instead of 0.01) and then enable bilinear filtering on your sprites. You will lose the pixel-perfect outline of your sprites, but if your using this on far away objects (eg. clouds) the player probably wont even notice.

Also, pixel-based movement will always be jerkier than sub-pixel world based movement (which can lerp between pixels without just jumping from point A to point B in a single frame). It’s not a silver bullet and it sometimes takes some experimentation to see if the effect is worth it. If you are using pixel based movement however, turning on vsync under the quality settings will also help prevent too much sprite-jumping, owing to the fact that you can’t use time.deltatime to smooth our your frame-to-frame movement.

 

Tutorial: Installing HaxeFlixel

Category : HaxeFlixel, Tutorials · No Comments · by Jul 1st, 2015

When I first started using HaxeFlixel, the biggest turn off was definitely the giant stack of programs I needed to install. Worse yet, I had no idea what half of them even did so I just had to blindly install them all and hope that nothing broke along the way.

Now that I’ve had a bit more time to use HaxeFlixel I realize the install process isn’t as daunting as it first seems. In fact, it’s pretty straightforward once you understand what everything does.

The following guide is a lot longer than what you’ll find on the HaxeFlixel website, but the idea is to explain the individual components that make up the install process. This is so when something breaks you’ll hopefully understand how to fix it. When I first started using HaxeFlixel the website I was downloading the libraries from went wonky, fell over, got a bucket stuck on its head and then one of the components went completely bonkers. I didn’t know what the hell the component even did so I just deleted everything and started again.

Note: This guide assumes you are installing on Windows.

Step 1. Installing Haxe.

What the hell is Haxe?

haxe

Haxe is the foundation of HaxeFlixel. It’s a framework that uses it’s own language to export to many other languages. It can export to Javascript, PHP, C++, C# and more! Writing Haxe is a bit of a combination of C#, Python, Javascript and a few other Haxe specific features like Macros thrown in. Haxe is what you’ll be writing in for HaxeFlixel, which is both a blessing and a curse. One one hand you have the entire Haxe community for when you run into issues, but on the down side most of your questions will be HaxeFlixel specific, making the official Haxe forums a bit useless. But in my experience just about every question about Haxe in general has already been asked so as long as you do some searching you’ll find an answer.

Ok so how do I install it?

Visit http://haxe.org and download the Windows installer.  Once it’s installed, go to “Start > Control Panel >  Search for Environment Variables > Edit system variables” and then click the Environment Variables button. In the screen that appears you have two types of variables, local at the top and system at the bottom. In the system variables check that you have a variable called “HAXEPATH” set to the same directory you installed Haxe.

step1_installingHaxe_variables

 

Note: If you are installing Haxe through Chocolatey sometimes the environment variable will be installed under “HAXE_PATH”. It should be changed to “HAXEPATH’. You might need to restart your computer after changing this variable. I’ve also noticed that sometimes it wont setup this variables at all, in which case you’ll have to manually add it in. Also make sure you have “NEKO_INSTPATH”.

 

Step 2: Running HaxeLib

When I first started with HaxeFlixel the tutorials made it seem like I had to install OpenFL manually. This is probably where everything starts to go sideways for most new users and it’s not the best idea to be installing all the packages by hand. Instead, Haxe comes with a  a very handy tool called HaxeLib. HaxeLib is a package manager similar to Nuget, npm, Bower or other tools. Now that we have Haxe installed we don’t actually need to install anything else manually, we can just cram stuff into the command line and let it install what it needs. Huzah!

To start, open your command line by going “Start > Run” type “cmd” and hit enter. This should open your command console. Next, enter these commands one at a time:

 

Timeout Errors: If you start getting timeout errors when using Haxelib, just wait 10-15 minutes and try again. Sometimes it gets hit by heavy traffic and sometimes (rarely) it goes down completely. If you are getting the timeout errors for an extended period of time you can download and install the packages locally by visiting lib.haxe.org directly. Once you’ve downloaded the correct package, in your command line make sure the path you are at contains the zip file and then replace the keyword ‘install’ above with the keyword ‘local’ – this will make haxelib install from your local .zip file instead. Also just make sure that you replace ‘lime’ with the full zip file name of the download (which will look something like “lime-2,5,0.zip”).

What the hell is Lime and why am I installing it?

Lime is the most basic layer of our rendering engine. It’s a very low level system that supports many platforms, such as Flash, HTML5, as well as native platforms like Windows and Android. It’s part of the glue between Haxe and the devices you compile too, plus it has one of the best icons around. Look at it! It’s a lime and a cube!

Lime alone can be quite difficult to write too, which is where OpenFL enters the scene – it’s a layer that sits on top of Lime and gives it a much nicer API to program against.

OpenFL? How many of these things are there?

openFL

OpenFL is a framework that is built to run on top of Lime. It’s a rewrite of the Actionscript3 library with some extra additions thrown in for device support. It’s very cool and gives us the ability to write in framework that is a lot closer to Actionscript. Without OpenFL we would have to write in OpenGL directly, which isn’t fun for most indie devs. We do lose out on some of the advanced functionality you get with Lime by having direct access to OpenGL, but from what I’ve seen that’s rarely an issue.

So why does this matter for us? Well OpenFL is what allows the “Flixel” part of “HaxeFlixel”. Flixel is a flash game engine written by Adam North, but since Flash isn’t that flash these days (HA!) some smart people re-wrote it in Haxe on top of the OpenFL engine (and OpenFL lets us export to more platforms than just Flash). That’s why some people refer to OpenFL Actionscript 4 and HaxeFlixel as Flixel 2.

Now that we’ve already installed Lime, we can install OpenFL to give us a nice API on top. In your command line run the following one at a time:

This will install OpenFL on your computer. Note that in this case we didn’t install this through haxelib because Lime will take care of setting up OpenFL for us.

One that is done we need to choose what platforms we want Lime to build to. You’ll notice that we don’t need to setup HTML5 support, it’s setup by default.

If you also want to build to Android, you can run the following:

Warning: If you do not plan on building to Android and you have never installed the SDK before, do not run this command. It will download an absolute craptacular amount of files and require you to do some manual steps in between to setup Java developer kits. I would actually recommend setting up all this in advance manually by following this guide on the Android site and then coming back and finishing this install.

Step 3: Installing HaxeFlixel

Between all these libraries and frameworks we actually still need to install HaxeFlixel! We have our base setup now, which looks like:

techstack

So our last step is to run the following.

This will install Flixel from the haxelib library, plus it will download a set of tools that make development much easier.

When you setup flixel-tools you will be asked if you want to setup a flixel alias in your console. It is highly advised you set this up. This allows you to write shortcut commands like ‘flixel tpl’ to setup a boilerplate project ready to go.

You will also be asked what IDE you are using. Don’t do what I did which is press a random number and hope to fix it later. Whatever option you select will determine what format your projects get created in (using the command alias above), so if you choose Flash Develop you will get .hxproj files, but if you choose IntelliJ you will get .idea files. If you don’t know which one to choose, just select Flash Develop.

Note: It is possible that after you’ve installed Haxe you can just skip to the command above. Lime and OpenFL are marked as dependencies that haxelib will automatically download when you install flixel. However, I recommend setting them up separately just so that you can do any extra steps you need like setting up Lime for windows/android.

Wait I thought we were installing HaxeFlixel? This is just Flixel.

flixel

Confusingly, Flixel is actually HaxeFlixel, it just doesn’t seem like it. Because haxelib is a collection of libraries written in Haxe, the version they contain is the actually the Haxe version of Flixel. This can be strange for new users because your downloading a framework called Flixel, but everyone keeps calling it HaxeFlixel.

HaxeFlixel is more of a collection of tools and frameworks under the umbrella project of HaxeFlixel, all supported by a core group of open source developers, rather than a single program like Unity or Stencil. So when you get HaxeFlixel, you’re actually pulling in several different tools and libraries (OpenFL, Lime, Flixel etc.) which all combine together to make a game engine. It’s both what makes the project so cool, but also very confusing to get started.

 Step 4: Installing Flash Develop

Visit www.flashdevelop.org and download the latest version.

Once you’ve installed it, open it up and go to: “Tools > Install Software” and tick “Standalone debug flash player”. This will download the Flash debugger we need for our project. At this point we can create a new blank project either by using the command line, or we can download a template that allows us to create a new flixel project from inside Flash Develop.

I also recommend downloading and installing the templates from this page: http://haxeflixel.com/download. If you are still using Flash Develop, download ‘FlashDevelop .fdz template’ and then run the file it gives you. You will probably have to restart Flash Develop. There is also a package just called “Flash Develop Template” which is just a raw dump of the boilerplate project – this can be handy if you want to customize the project template and use that as your starting point (I have a slightly modified version I use for game jams).

Step 5: Have a victory beer

Everything should be setup ready to go now. There’s some tricks you can now do like ‘haxelib upgrade’ to update all the libraries and plugins you’ve downloaded. and there’s some great plugins out there that you can also download (don’t forget that as long as it doesn’t need to render anything, pretty much any Haxe plugin can be used in your game). I may do a follow up post on getting started with Flash Develop (including the extremely finicky debugger) and cover some good boiler templates that are out there to get started.

 

Crappy Lion Safari – Post Mortem

Category : Game Jams, Post Mortem · No Comments · by Jan 27th, 2015

 

cls_screen2

The 48 hour Toronto Global Game Jam for 2015 is complete and my little game is finished. The theme for this year was “What do we do now?” which, as far as themes go, is pretty uninspiring. Going into the game jam I knew I wanted to do something with a ‘spinning plates’ style gameplay where the player is dashing backwards and forwards around the screen trying to keep things moving. I was thinking of maybe doing a cooking game or perhaps a sinking submarine where it’s falling apart and you are trying to run backwards and forward fixing things to stop it from imploding. Once they announced the theme though I figured that there needed to be two people present so the question could at least be asked, eventually settling on having tour guides trying to lead angry tourists through a crap zoo. The end result was Crappy Lion Safari.

cls_making1

The not so good:

Managing States: The more I work on these games the more I’m noticing that I run into the same problems over and over. At the top of that list is managing states. It always in the last 30% of the project that I find myself hacking in solutions to manage this, and it never works out well. In Odds Mansion I had a very basic state machine for the player (which worked quite well), but never botherd with the rest of the game. That meant the whole UI was a complete hackjob of “When X happens, do C, D, G, not F, maybe H…” every time the user clicked something. With Crappy Lion Safari I didn’t have any sort of state machine at all. Instead I had properties like “IsBeingLedByPlayer” and “IsAtCage” and “IsAutoWalkingAngrily”. This led to all sorts of wonderful hacks where I’d check “IsBeingLedByPlayer” in one location, but then forget to consider that an animation could be running in another. Anyone who stopped by to play the demo during the 48 hour game jam immediately became accustomed to dead bodies creepily sliding from cage to cage taking photographs…

DOTween oddities: There’s not much I could have done to avoid it, but I found some really strange behaviors with DOTween. I wasted about 3 hours Sunday morning trying to get some simple alpha fading to work only to figure out it was something to do with re-using pooled objects. I have an object pooler I use in my game, and it seems (and I need to test this) but when you create a new sequence it seems to run in its own little world that doesnt take into account the current state of your code – this means if you pull an object from your pool, reset some variables and then pass it to a new sequence, the sequence is unaware that the object even exists unless you pull the pooled object inside the sequence as well. Super weird and I need to do some testing.

Not making a full screen game: I wanted to keep the game at 500×500 for simplicity, but it certainly didn’t stand out as much as some full screen games people had running. Nobody seemed to mind and it pulled it’s fair share of people in to give it a go, but I think for my next game jam I’m going to try and make something I can leave running in full screen.

cls_making2

The good:

Cinematic handler – After Odds Mansion I realized I needed a better way of handling cinematic’s. I ended up building a little system that allowed me to add manual steps using player feedback or progressing automatically by building some helper methods on top of DOTween. Basically you push an event into it using a callback, which by default pauses after every sequence. The player then taps the mouse and it resumes the tween. Getting the short intro and end game animations done was probably the fastest part I worked on. This also let me use a much better tutorial system than I’ve had in my games before (I think).

Not bothering with sounds: I never really considered it until the last day but not bothering with sound effects or music worked out great for a game jam. It didn’t really occur to me until another jammer mentioned it but when people are playing your game they are not going to be able to hear the sound anyway. If you planned ahead and bought speakers with you maybe then they can hear, but if too many people are also blasting sound effects it’s just going to get drowned out. Obviously this is only relevant for game jams but it saved me a ton of time. Originally I wanted a little whistle sound effect like Pikmen so players knew when they had picked up and dropped off, but players wouldn’t be able to hear the sound anyway. So at the last second I threw in a little bounding box around the tourists, which worked out great.

Artwork – Super simple and ended up drawing a lot of attention. What was meant to be mostly placeholder art got good feedback so I just left it as it was with some small cleanup on Sunday. Funnily enough the main reason I went with a zoo theme (apart from the reasons above) was because when I was uploading screenshots of all my games to this site I realized most of them had dark backgrounds. I wanted to do something colorful to break up the pattern a bit 😀

cls_making3

 

Overall I’m happy with how the game turned out – sure it’s small and it’s not exactly minecraft, but just making a game in 48 hours is a challenge I wasn’t sure if I could ever complete. The Toronto Global Game Jam was better than I could ever have hoped too. Cool people all round and amazing organizers 😀

Getting prepped for Toronto Global Game Jam 2015

Category : Game Jams · No Comments · by Jan 22nd, 2015

Tomorrow night the Toronto Global Game Jam starts! I’m signed up, my bags are packed, laptop is charged, I’m ready to go.

logo

I registered as a Solo dev instead of joining a team since this will be my first foray into the GGJ – I figure if I go down in flames clutching my copy of Unity like a parachute, at least I’ll be the only victim. But it’s going to be great to meet some of the Toronto folk and seeing what crazy crap they come up with. Who knows, maybe next year I’ll be able to join a team if my skills can cut it.