Archive for the ‘Game Development’ Category

Nov 21

Gamepad support in Unity. It looks deceptively easy, if you look at the Input API. Just a collection of buttons and axes, Right?

Of course, the devil is in the details. You can go ahead, get your button mappings set up using your 360 controller or your PS4 controller or your Logitech or what-have-you. Run it, and it will all work great. On your gamepad. On your OS. The minute your game goes to someone who has a different brand of gamepad, or sometimes even a different OS, your gamepad support breaks. Up and down on the right analog suddenly rotate the camera left and right instead, none of the face buttons work, and other controls are similarly mismatched. Why? Because no one in the game controller industry can seem to agree which button is the first button, which axis number should correspond to up and down on the left analog stick, etc. The situation is especially bad with XBox-family controllers, with these correspondences being different on all 3 major OS’s.

Of course, you can make players go through a one-time controller set-up, a digital game of Marco Polo where the game asks you to press a particular button and then listens to figure out which button that maps to on your controller. But, that is not really an acceptable user experience today.

Imagine if we still had to write different code to accommodate different graphics cards, like we did with the first generation of 3D accelerators. It would be a total nightmare! Yet, this is pretty much the nightmare that we face when trying to support game controllers. Very early on, the concept of the Hardware Abstraction Layer (HAL) was applied to 3D graphics accelerators, so that, to our code, all accelerators looked and worked the same (save for differences in capabilities). These days, rarely do we have to even think about whether a user is running with an nVidia or AMD/ATI graphics adapter.

Unfortunately, no such animal exists for gamepads at the system level, at least not to the degree that we can ask a system-level library like DirectX, “Give me the status of the left analog stick’s Y-Axis”, and have it mean the same consistent thing across devices. The closest thing we have is the USB HID specification, but it is really made for very generic input cases, and specifically does not solve the problem of establishing consistent button/axis mappings across devices.

So instead, we are forced to build databases of controller configurations, and build (or buy) our own abstraction layers that hopefully support every controller under the sun, knowing that somewhere, someone has a controller that has not been accounted for and is incompatible.

Unity also does not help much in this regard, which is a shame. A well-documented lack of run-time configurability of inputs (as recent as 5.2) all but assures that serious game development projects must come to a point where they need to build or buy a replacement to the built-in input system.

For purposes of Dehoarder 2 gamepad support, I’m going to try the InControl component from Gallant Games. It seems to integrate the best, even allowing me to hook in to the newer uGUI event system, so that I can use built-in Unity functionality like controller-based menu navigation.

I could have tried building something like InControl myself, though it would have taken me dozens, if not hundreds of hours to get it working right. Plus, I’ve only ever had experience doing such code on the PC, not OSX or Linux platforms. All of that mess, vs. $35 for something that has been well-polished and likely supports more scenarios than I’d ever need. Easy decision.

I’m still trying to find a good way around paying $65 for a library that allows me to inject icons (like controller buttons) into my text, though…

Aug 8

Laser Frenzy EndA friend and I were discussing recently some of the special physics requirements of block breaker / Breakout / Arkanoid style games. When I put together the physics for Breaking Block, I already had a pretty strong idea of how I wanted the physics to work, though I noticed that the internet had mostly half-answers. I found that many people were asking about Breakout-style physics. Since complete information is so scarce, I’d like to share some lessons that I’ve learned while developing the physics for Breaking Block.

Be Wary of Using Physics Engines for Such a Simple Case

Physics engines are by their nature generalized, and a block breaker game, when implemented properly, has some very specific physics rules. The generalized rules of engines get in the way. Beyond the obvious things like needing to disable gravity and ensuring preservation of kinetic energy, sometimes, no matter what you do, an object takes a weird bounce in an engine-based rigidbody collision, and the angle of deflection is nowhere near acceptable (i.e. ball bounces off corner of block and travels horizontally, killing the game).
You can try to hack around this stuff all you want. At the end of the day, though, just applying movement in script using angle and velocity is cleaner, more performant, and more correct for this case. Using a physics engine for a basic block breaking game is the proverbial “Shooting a fly with an elephant gun”. Consider that the physics rules for the original arcade Breakout weren’t even implemented in a computer program at all; the rules were hard-wired into logic circuits.

Simple Ball Reflection for blocks

Handling deflections off of blocks and walls is trivial if you keep track of your ball’s angle as a direction vector, and keep your blocks orthogonal. On a vertical hit, just invert the y component of the direction vector, and on a horizontal hit, invert the x component. One common question is how to tell whether a hit is vertical or horizontal. You could inspect the collision details and look at surface normals, but with orthogonal blocks, that’s a bit more complex than what is needed. Just take the difference in position (delta) between the ball and block, scale it by the inverse aspect ratio of the block (for example, if the block is twice as long as it is high, divide the x component of the delta by 2), and see which component of the delta is smaller. A smaller y means a vertical hit, and a smaller x means a horizontal hit.
Here’s an example, with an additional Sign check added to make sure the ball is traveling toward the block. That check prevents the ball from destroying two adjacent blocks simultaneously.

var delta = (ball.transform.position - block.transform.position);
// apply aspect ratio via the scaleFactor vector
// For a horizontal block twice a wide as high, use Vector3(0.5f, 1f, 1f)
// For a vertical block twice as high as wide, use Vector3(1f, 0.5f, 1f)
// For a square block, use Vector3(1f, 1f, 1f), and so forth.
if(Mathf.Abs(delta.x) >= Mathf.Abs(delta.y))
    // scaled delta x was larger than delta y. This is a horizontal hit.
    if(Mathf.Sign(-direction.x) == Mathf.Sign(delta.x))
        ballDirection.x = -ballDirection.x;
    // scaled delta y was larger than delta x. This is a vertical hit.
    if(Mathf.Sign(-direction.y) == Mathf.Sign(delta.y))
        ballDirection.y = -ballDirection.y;

Keep the Ball In-Bounds, No Matter What

Don’t rely on colliders and other softer barriers to keep the ball in-bounds. For instance, a ball might get stuck between a moving block and a wall and pop through. Things get chaotic. Include a hard bounds check, and reflect the ball in the appropriate direction if it leaves the bounds of play.

if((direction.x > 0f && transform.position.x > fieldMinimumX) ||
    (direction.x < 0f && transform.position.x < fieldMaximumX))
    direction.x = -direction.x;

if(direction.y > 0f && transform.position.y > fieldMaximumY + 0.1f)
    direction.y = -direction.y;

Let the Paddle Control the Ball Angle

It is very common for the contact position between the ball and the paddle to govern the angle the ball will take. This is very easy to do using the horizontal difference in position between the ball and the angle. Remember to take into account any change in paddle size if your game allows it. More about that ClampBallAngle() function in a moment.

var newAngle = (
        -(ball.transform.position.x - paddle.transform.position.x) * 60f / enlargeScale
    ) + 90f;
newAngle = ClampBallAngle(newAngle);

Prevent Degenerate Angles

In every FUN block breaking game I’ve played, I’ve never seen the ball travel at an angle that was close to horizontal or close to vertical. Horizontal angles are not fun because inevitably the player winds up waiting for the ball to trolley-car endlessly between the two walls. Vertical angles are not fun because they make it too easy to aim shots and volley balls with minimal effort. Steps need to be taken to prevent the ball from taking one of these angles.
If you are only using reflections to modify the angle everywhere else, then this only needs to be done when the ball is launched or collides with the paddle. This function is written with that in mind, a more general solution would be needed if the angle needs to be fixed in other situations. Note that in this case, it is much more convenient to express the ball angle as an actual angle rather than a direction vector.

private float ClampBallAngle(float angle)
    if(angle > 150f)
        return 150f;
    if(angle < 30f)
        return 30f;
    if(angle <= 90f && angle > 75f)
        return 75f;
    if(angle >= 90f && angle < 105f)
        return 105f;
    return angle;

Make Sure Your Collisions Happen

One drawback to not using a physics engine for movement is that you lose the engine's ability to do some of the more dynamic collision detection for cases where an object completely passes through another between updates. There are several ways to compensate for this:

  • Use a shorter update loop, and make sure it is a loop with a guaranteed time interval. In Unity I am using FixedUpdate for the really important physics, and have the fixed update rate set at 100fps.
  • Limit your top speeds. Do the math to ensure that an object at its top speed cannot move more than 25% (arbitrary number, adjust as necessary) of the way through another object in a single update frame.
  • Use raycasting. Cast a ray from an object's previous position to its current position to see if it passed through anything. I did not wind up having to take this approach with Breaking Block, but it is viable and I have used it in past games. Unity actually has a very handy SphereCast() function that is like a raycast, but accounts for an object's radius.

Track Dead-Object State to Prevent Incorrect Simultaneous Collisions

This is critical to things like multi-ball play, laser power ups, anything that makes it so that a block can be hit by two separate objects in the same frame. It may not apply to all engines, but in Unity at least, when you request that an object be destroyed, the actual destruction is deferred until the end of the update loop. This causes a situation where a block can be scored as destroyed twice, by two different balls, by a ball and a laser, by a ball and an alien, etc.
To prevent this, the first collision should set a death flag on the block. The collision code should check this flag, and take no action if the block is already dead.

In Conclusion

Hopefully these tips will help you in your quest to build a block breaker game. A block breaker game is a good exercise for any aspiring game developer, with a strongly-defined problem, limited scope, and lots of room for creativity.

City LevelTen days ago, I still had 11 boss levels to complete for Breaking Block, along with all of the special mechanics that make the boss levels, well, special. Also, I had 42 more regular levels to create. And I semi-firmly said I would release in June. Still I did not panic, because I knew my content creation tool was solid.

Today I am down to one boss level remaining (the final boss), and 12 regular levels remaining. I’ve been focusing mostly on boss levels since those were further behind and require many times more effort, switching to regular levels when I was burnt out on creating boss mechanics. Overall, this worked out well.

I’ve never made quite this much (in quantity) content for a game before. The next closest is EARL’s Warehouse, with its 39 levels. Even with my map editor, though, creating new maps for EARL’s Warehouse is fairly time-consuming.

I’m very glad that I took a little time early in the project to make level creation for Breaking Block as simple and quick as possible. If I have an idea in mind of the level I want to create, a level can literally be made in 10 minutes. Coming up with the ideas takes more time than expressing them, and that is how it should be, and how you know a tool is really doing its job.

Here is an example level design file for the first boss in the game:

    V     R-    R-     V
    |V Y-Y-Y-Y-Y-Y-Y- V|
     |  Y-G-Y-Y-G-Y-  |
     D-  Y-Y-Y-Y-Y-  D-

#anchorblocks 1 1 27 28 MovingBoss
#object MercuryBoss 0 9.25

That’s it. Just a few simple lines of text. Any line that does not start with “#” is interpreted as a row of the playfield, and the characters in that row represent the blocks to be created. In this map, we have ‘V’ for violet, ‘R’ for red, ‘Y’ for yellow, ‘G’ for green, ‘D’ for gold, ‘$’ for deadly plasma, and ‘@’ for the boss target blocks. A ‘-‘ dash modifies the preceding character to create a horizontal block, and a ‘|’ vertical bar modifies the above character to create a vertical block. If neither modifier is used, a small cubic block is created.

Lines starting with “#” are commands. The “#object” command creates a Unity prefab, and this allows me to easily import the special behavior of the bosses. The “#anchorblocks” command allows me to anchor a set of blocks to the named object’s transform, so that they can be moved as a group. Whenever I need to do something special for a level design, I can just create a new “#” command.

Here is how it ends up looking in game:

Easy to use, easy to explain, easy to extend. It’s even fairly easy to visualize the level from the text file. The one weakness I’ve found in this text-based approach is that sometimes things look a little different than you think, so it can be a little bit of trial and error to get things to look right. Still, even that iterative process is quick. And this design was about 1/10th the effort of writing a full graphical editor.

Of course, things can’t always be simplified this much, and I’m not suggesting I could have used such a technique to make EARL’s Warehouse level development more efficient. We can simplify where we can, though. I could just as easily made a level format where each block was encoded as an XML element. This then would have required me to write a visual level editor. Instead, I took advantage of the simple 2D design of my game to make a much more expressive level format.

With this design, given just a couple of hours I can have a few normal levels done, or implement the mechanics for a new boss. This means more content for less time, allowing me to promise 108 levels with 13 boss battles in short order.

If there’s enough interest, perhaps future versions of Breaking Block can allow players to exchange and play their own custom level files – I’ve already given almost enough information for any enthusiast to create levels.

Quite a few people have asked me in the past where I get the great music tracks for my games. I have found two great sources where it seems no matter what feel of music I want, they have something for me.

One source is Incompetech, with tracks composed mostly by Kevin MacLeod. He has literally hundreds of tracks, and you can easily search by genre or feel:

My other go-to guy is Dan-O. He also has well over 100 tracks available, arranged by genre. He even has a few vocal pieces in there:

When I’m looking for musical pieces, I like to just browse through both of their libraries, note any viable candidate tracks, then have a listen-off among those tracks, picturing the game in my mind. Usually I end up with too many tracks, and have a hard decision of which ones to cut out.

It always brings a smile to my face when I’m watching some internet video or playing a game, and a familiar track comes up, either one that I’ve used or one that I’ve filed in the back of my mind for future use. I’ve even heard one track from EARL’s Warehouse used in a TV commercial.

Both authors have released their works under a Creative Commons Attribution license. Just put them in your credits, and you are good to go, though they won’t mind if you give them a donation for all of their hard work.


EARL's Warehouse Proto to NowNext week will mark the one year anniversary of when EARL’s Warehouse was born as a concept and the prototype was started. As you can see from the picture, EARL’s Warehouse came quite a long way from its early builds to its latest test build.

Today, I thought it would seem fitting to discuss and evangelize a bit about the prototyping and iterative development that went on in EARL’s Warehouse on the eve of this development anniversary.

For the first prototype, EARL was nothing more than a cube floating on top of a box, and his warehouse just a grid of grey cubes. He didn’t even have a name at that point; the entire project had a placeholder name of Bloxxel. When he picked up boxes, they simply disappeared, only to reappear when placed. The physics sucked, and often EARL would suddenly jump to the roof. Beneath this rough implementation, though, my First Impressions team found a gold nugget of fun that came from moving boxes around a voxel-based world to solve puzzles.

Slowly, over time, features emerged from the prototype design. Just enough work was given to each area of the game each time it was touched to take it to the next level. Boxes gained powers. One map turned into four maps. Some sound effects and a couple of cool music tracks were added. Crude physics gave way to more refined physics with less roof-jumping glitches. Placeholder graphics were replaced with flat textures. New robots were introduced. Four maps turned into ten maps. More sounds and music were added. Physics calculations were optimized. Bumpmaps were added to the graphics. Robots and powers were balanced and tuned. Ten maps turned into 24 maps, and so on.

Prototyping and iterative development as exemplified above are both very important to independent game development. Both are crucial techniques for preventing wasted work.

An early, rough-looking prototype like the one inset in the picture allows rapid experimentation to see if an idea will work or is total garbage. For every prototype like Bloxxel that gets made into a game like EARL’s Warehouse, I have 3 or 4 prototypes I will never touch again, because the concept could not be made to work in practice. The sooner a project is runnable the better, because that is all the sooner you can determine if the project is gold or garbage.

Iterative development allows you to quickly gather feedback on whether a project is heading in the right direction. By adding a few working features at a time to a runnable project, you can spot wrong turns quickly and make corrections. If you do too much work without pausing to gather feedback, you run the risk of wasting a lot of work that can be expensive to undo.

When doing iterative development, it is also important to address the highest-risk elements of the project first, so that you can quickly identify and address any project-crushing issues that may arise. It is important to iterate across your project, touching all areas, and not get too bogged down in seeking perfection in any given area. When all relevant aspects of the project have had some work, then it is time to restart with the oldest aspects of the project, and apply insight gained from other areas of the project.

There are many ways to apply these techniques. One of the easiest is to use an established game engine like Unity 3D, GameMaker, or any of the other offerings that are out there. Nowadays, most of them are cheap, if not free. And if it’s not cheap or better, it doesn’t fit with the philosophy of inexpensive prototyping and iteration. A mature, well designed game engine lets you easily play around with and re-arrange elements to explore game concepts. Interactions can be mocked up and refined quickly and easily.

Another way to incorporate iterative development is to commit yourself to delivering a playable build of your project at the end of every work session. I do this, and it keeps me honest about making sure I am leaving things in working order as I iterate, and has other advantages as well: I am always ready to give a demo of all of my latest projects, if needed. If done right, it takes no more than 5-10 minutes to perform the build and do a quick smoke test. (Note: Always keep your old builds for a while in case you discover a showstopping issue deeper than a smoke test can penetrate, especially if you demo often.)

I find that keeping a prioritized backlog of small-to-medium sized tasks serves to both keep me productive, and to promote iterative development. Each work session I will look over this list, pick out a few items I would like to deliver, and then focus on delivering only those items, getting sidetracked only if some other task blocks me from completing those items.

Some of these techniques I discuss from a solo developer point-of-view, but many have team-based analogues that they were distilled from. Nightly builds for team projects are common, as are Scrum-style product backlogs containing stories broken into tasks that are then assigned to individuals or teams. The basic concepts of delivering early and often are still there, and are at the heart of any prototyping or iterative development effort.

Iteration. It’s one of my keys to getting things done.

So while I climb down off this soapbox here, I’ll just dust off and say that testing continues to progress well for EARL’s Warehouse, and I am still on-target for release on September 14 at the Ohio Game Dev Expo. I hope anyone near Columbus who is reading this blog will be able to stop by and see all of us Ohio game developers there. As game development winds down, my preparations for the expo will be heating up.

One of the really cool reusable components to come out of the development of Dungeon’s Fortune and EARL’s Warehouse is my Voxel Engine (think Minecraft blocks). I’ve spent the last couple of weeks polishing this technology further, gearing up for an eventual release on the Unity Asset Store.

I really think this is something that a lot of developers could use to rapidly create maps for games. With a map editor, and a couple of drag-drops, it is really easy for me to create a voxel-based environment like the one in EARL’s Warehouse. I recently did some integration between my voxel engine and the Unity physics engine, and the results are promising (EARL’s Warehouse had used custom physics).

Look for more information to come about the Aedific Voxel Engine, including the expected release feature set. Meanwhile, if you are interested in being an early adopter of this technology, helping to test and enhance it, please drop me a line, and I’ll hook you up with a serious discount.

Also, I just went and got all the parts for my brand new file/repository/streaming server. Finally my server technology will be from the current millennium. I’m looking forward to having a proper source code repository. Another thing that makes me smile about the new server setup is the streaming capability, which may eliminate my need for a HTPC.

Time to go dust off my system builder hat.