Wednesday, August 28, 2013

Delayed

Just wanted to post a quick note to say that there's a slight chance I won't be able to keep my promise of "at least one Turncoat Dev Diary entry a week" promise  for this week. My next post is rather long and involved -  an exploration of touch controls for first and third person games and the process I went through trying to adapt my game's controls to the touch screen - and I've been on travel all this week with a very busy schedule. Worst case scenario, I'll have the next diary entry posted by next Monday, though I'm hoping to get it out earlier.

Wednesday, August 21, 2013

Turncoat Dev Diary: Prototyping Player Game Mechanics, Episode II

(This is part of a series. The first post in the series is here.)

As I started working on the basics of movement, I decided that my prototyping model needed a little something extra. I want my character controller to support "physics bones", which are bones that aren't pre-animated, but instead are controlled by the physics engine. You might use physics bones if a character has a pony tail, for example, so that the pony tail moves naturally. If a character has an item hanging from their belt, you might put a physics bone on it to make the item bounce around as the character walks. You can also use physics bones to fake cloth and hair physics. The results aren't as good as you get from true physical simulations, but those are often too processor intensive to do in real time, especially on mobile devices. You can get surprisingly good results by faking more complex simulations using a number of constrained physics bones.

In order to ensure physics bones work with my controller, I went back and added a pony tail to my prototyping character. Well, more like a pony-spike-out-the-back-of-the-head, but it'll work.


Because these bones are not standard parts of a bipedal character, they're not part of any of the animations I have. By default, bones that aren't part of an animation just move along with the nearest ancestor bone that is part of the animation. In our case, that's the head bone, and the result is less than realistic.


To get the pony tail to behave the way I want it to behave, I have to add colliders to each of the new bones and make them all part of the physics system. It was a little tedious getting the colliders set up for the pony tail. I have no idea why Unity places colliders, by default, at the head of bones rather than at the mid-point of the bone. While it might make some sense on paper since the head of the bone is its pivot point, in practice, you're almost always going to want the collider to be placed so it covers the length of the bone. If the colliders defaulted to the midpoint of the bone (halfway between the tail and head), it would take a lot less time to set up physics bones and skeleton colliders.


Once I placed all the colliders and added rigid body physics to each of the bones, I fired it up to try it out. The bones were definitely affected by gravity, just not in the way I wanted; the pony tail fell right to the ground and bounced around on the floor because I forgot to connect the bones to each other with joints.


Joint components are Unity's way of telling the physics engine that certain things should stick together. There are several types of joints in Unity, but the one I want here is called a Character Joint. Adding a character joint to each of the pony tail bones will keep them connected to each other, but will allow them to swing and twist within set limits. After some playing around, I came up with these values for my pony tail.


If this were a real model, and not just a prototyping one, I'd probably spend a lot more time tweaking these values to get them just right. Since all I really care about right now whether parts of the character can interact with the physics engine properly, it doesn't make sense to spend a lot of time tweaking these parameters. Testing it out, it looks okay. Or, at least, it looks okay as I can tell without being able to move the character around.


I guess I know what I need to do next: basic movement controls. I'm eventually going to work on touch controls, since this will be released on iPad, but for now, I'm just going to use keyboard and joystick to get the animations working. Translating these types of controls to touch is, I think, going to be a fairly time-consuming task, so I want to tackle that by itself separately.

Unity's Mecanim system lets you automatically transition between different animations or even combine animations by building a state machine. You can pass different parameters into this state machine from your code and set it up to transition between various animations based on the values you pass in.

I started with a state machine provided by Mixamo with one of the motion packs that I bought from the Unity Asset Store, but I had to fix quite a few things to get it functioning to my satisfaction, then I expanded on it to get the basics of movement covered. This state machine includes stand, turn in place, walk forward, walk backward, run forward, run backward, jump in place, and jump while walking.

Here's what it looks like in Unity's editor:


I'll have to add stealth movement, crawling, and taking cover to my state machine later, but I want to get these basics working well before I start on the more complex parts. Down in the lower left corner, you can see the parameters that can be passed into my state machine. Here's how a parameter gets passed in from code:

Animator anim = GetComponent();   
float vertical = Input.GetAxis("Vertical");
anim.SetFloat("Speed", vertical);

Pretty straightforward. Just grab a reference to the animator component that represents this state machine and use SetFloat, SetBool, SetInteger, etc. to pass in whatever value is needed.

The orange Idle state in the middle of the picture above is orange because it's the default state. That means that when the level starts, the character will immediately start animating using the Idle animation, which is just a short looping animation of standing still. Using an animation for the idle state is more natural looking than just having the character stay frozen in place when not moving.

Every white line in the state machine is a transition that defines when the character should switch from one animation to a different animation.  For example, if the Speed parameter becomes greater than 0.1, the character will automatically transitions from the Idle animation to Forward Locomotion because that's the condition I've specified for it:


This ability to move between animations based on parameters is pretty neat in and of itself, but this system is even more powerful than that. Forward Locomotion isn't actually an animation the way Idle is. It's what Unity calls a Blend Tree, which is a grouping of animations that can be interpolated together to create new animations based on input parameters, to create new animations. This allows you to take, for example, a walking and a running animation, and blend them together to create a fast walk animation. Here's the blend tree called Forward Locomotion that gets fired when a character starts moving forward:


This blend tree takes two parameters - Run and Direction. The Direction parameter goes from -1.0, representing turning as far left as possible, to 1.0, which represents turning as far to the right as possible.  Run, similarly, goes from -1.0 representing full backwards motion, to 1.0, which is full forward motion. This particular tree will only ever get Run values between 0.0 and 1.0, however, because there's a separate tree for handling backwards movement.

This tree will automatically create new animations by mixing the run and walk animations together based on the value of the Run parameter. If Run is 0.0, the character will walk. If Run is 1.0, they will run. For any value in-between, it will mix the two animations to create something between a run and a walk. Similarly, the tree will also interpolate between the walking forward and walking left or right animations based on the Direction value so that the character turns left or right naturally. All the hard work of interpolating between multiple animations is done for you. You just pass in two parameters in and everything else gets handled for you based on the way the state machine is set up.

It's a pretty great system, and I'm mostly happy with the basic locomotion as it exists right now. There's a few things I don't like, however.

The first is that the arc left and arc right animations I have from Mixamo all seem to have a problem. I'm not exactly sure what the root cause of the problem is because I don't have access to the source animations, but whenever you transition into running or walking all the way to the left or right, the camera starts moving in a jerky, accordion-like manner that just looks terrible. It's not as noticeable with the walk animations, but when you start running, it's really noticeable.

But that's not a problem with the controller or state machine, it's a problem with the animations themselves, and I can replace those at any point. I'm not going to worry about this problem for now. I'm just going to make a note to find replacement animations that don't have this problem or else to buy the full version of these animations and fix the problem myself. If I can't do either of those, then I'll get rid of the Direction part of the blend tree and turn the character left and right in code, which is the traditional way of turning a character that uses an animated walk cycle.

The other problem that I notice is that there's no way to do a standing forward jump. The state machine jumps forward if you're already moving forward and jumps straight up in place otherwise. If the forward button is pressed (or the joystick is pushed forward), but you haven't hit that 0.1 Speed threshold yet, you jump straight up, which doesn't feel like correct behavior to me.
Are you wondering why there's both Speed and RunSpeed represents the actual value taken from the Y-axis of the joystick (if not using a joystick, Speed is 1.0 if the forward button is pressed, 0.0 otherwise). Run, on the other hand, is a calculated acceleration value that builds up over time based on SpeedSpeed is used to determine when to transition to a forward or backward movement, but Run is used to interpolate between the walk and run animations in a natural manner.
My first thought for fixing this was to simply change the transition to jump forward if Speed is greater than 0.0 rather than 0.1, but I realized that 0.1 threshold wasn't the problem. The problem is that there's currently no transition that goes directly from Idle to Running Jump. To fix this, I need to add a new transition from Idle to Running Jump, and then make sure the transitions to the jump states are never ambiguous. I also needed to add transitions back from Running Jump to Idle if the character's not longer moving forward, otherwise there's a little stutter step as the state machine has to go back first to ForwardLocomotion and then to Idle. Here's what my state machine looked like after tweaking the basic movement:


Happy with the basic movements, I decided to take my character out for a stroll around the level. She knocked over some barrels, which told me she was interacting with the physics engine appropriately, but when I got to the stairs or the ramp, she wouldn't climb.

Making my character part of the physics system isn't enough to get her to walk up stairs or slopes. The physics engine will keep her from walking through walls, but it won't handle changes in elevation. Dealing with that requires some logic.

There's two possible ways to fix this. I can write code to handle elevation changes needed to properly traverse stairs and slopes, or I can use the provided CharacterController class, which already contains code to deal with slopes and stairs.

My favorite kind of code is the kind of code you don't have to write at all, so I decided to try using the provided class before setting off to write my own physics-friendly replacement. Unfortunately, this particular class is the one I talked about in the last post that turns your character into a giant floating pill in the physics engine. Once I added a CharacterController component to my character, it instantly started doing wacky things like walking on air.

I added the character to the same Player Collision layer as the bone colliders. Because that layer is set to not interact with itself, it stopped the problem. Suddenly, my character could walk up stairs, climb slopes, and just generally move around the level pretty naturally. But, there were new problems. For one thing, my physics bones in the pony tail weren't bouncing off the character's back, they were passing right through them. For another, I was back to interacting with the physics objects like the barrels on my test level, as if I was a giant valium pill instead of bipedal creature.

I tried moving the physics bones in the pony tail to a different layer. That caused them to begin bouncing off the other bone colliders, which is good, but it also caused them to interact with the character controller, which is bad, because it puts us back to crazy stuttery walk-on-air time.

All is not lost, though. Taking a step back to think about what should interact with what, I realized there was a way to make this work. I don't want any of the bone colliders - neither the physics bones, nor the regular ones - to interact with the CharacterController because that causes weird, undesirable behavior. I also don't want the CharacterController interacting with props or moveable items because I went through all the effort of setting up bone colliders to do that. I do, however, want the CharacterController to interact with the terrain, but I don't really want all the bone colliders to do that because it would be redundant.

That means all I need to do to get this working is to add a few more layers. If I move the CharacterController to a different layer than the bone colliders and put the physics bones back on the same layer as the rest of the bone colliders, then create separate layers for the terrain and moveable objects, I can then use the physics preferences to make everything work correctly.


With these settings, terrain is handled by the character controller, props are handled by the bone colliders and ne'er the two shall meet. Props and terrain still interact with each other, which is necessary because the props would fall through the floor if they didn't.

This seems like it should work. Let's see if it does.


Ahhhh....


That's not a bad start as far as I'm concerned. Time to start working on more advanced movement, like taking cover, as well as switching between first and third person perspective. But not today.

Next Up: Prototyping Player Game Mechanics, Episode III
Previous: Prototyping Player Game Mechanics, Episode I

Monday, August 19, 2013

Turncoat Dev Diary: Prototyping Player Game Mechanics, Episode I

(This is part of a series. The first post in the series is here.)

The first game mechanic that needs to be nailed down is player movement. This is the most important mechanic to get right because it's on the screen all the time. Up to this point, I've just been navigating the prototype map using the stock first person controller that Unity provides. It's time to move past that and figure out the actual player movement and controls for the game. I'm sure we'll be tweaking these right up until release, but we at least need to get to a good starting point created.

I've been going back and forth in my own mind over whether the Escape game should be a first-person or a third-person game. Both have merits. For shooters, often the first person-perspective works better because it's easier to aim guns and other distance weapons from this point of view. For games that use melee weapons or that aren't primarily about combat at all (like ours), I tend to think that third person works better. From a storytelling perspective, I kind of want the main character visible on screen. They are the protagonist, after all, so I want the player to be able to see them. The high-level considerations seem to be pointing more toward third-person perspective.

But third person perspective falls apart sometimes. The situation in our game that seems potentially problematic for third party control is when you're crawling through the ducts. Space is tight and the player will be in front of the camera taking up most of the available space. That's going to make it impossible to see what's in front of the character and difficult to effectively control their movements.

On the other hand, there are times where first person perspective isn't ideal either. I want the player to have a number of options for hiding and taking cover. If using first-person perspective and the character does something like flatten herself up against the wall or takes cover behind a piece of furniture, it's going to be hard to see everything the player needs to see to effectively play the game. Those perspectives may be potentially disorienting as well. In real life, when you're hiding behind something, you can't see the stuff on the other side. But, in a game, you have to be able to see at least some of what's going on for the game to be playable.

Perhaps, the camera needs to be able to change perspective. Crawl into a vent? Move to first person view. Press up against a wall to hide? Force third person view. 

What about when both perspectives work, such as when simply walking or sneaking around the cell block? It seems like there are two possible choices there. We can either be opinionated and force one perspective or the other on the player, or we can let the player choose the point of view they want. I'm leaning toward letting the player choose, but I'm going to play wait and see before making the final decision on that. I think we need to let testers try it both ways and see the response.

Time to start building a character controller.

Of course, we don't have character designs yet, let alone completed 3D characters. So,  how do we prototype character movement?

We use this:


This is a free character from Mixamo designed specifically for prototyping. With Unity 4's Mecanim animation system and its ability to retarget motions, pretty much any animation designed for a bipedal character can be used with any other bipedal character. That means we can write a generic controller object for this prototyping character, then simply swap in the correct character model later once it has been completed. As long as our models are designed correctly and aren't radically different in their basic proportions, it should should just work.

Mecanim is impressive. The motion retargeting is some of the best I've seen and the importer almost always maps all the bones correctly regardless of the naming convention used or the number of bones in the model. The only downside to Mecanim is that it's still fairly new, so a lot of Unity users haven't moved to it yet and are instead sticking with the legacy animation stuff for their current projects. As a result, there's just not as much out there in terms of tutorials or available help. Mecanim makes it really easy to do the basics, but once you start going beyond the basics, you pretty quickly get into uncharted territory.

Uncharted territory can be fun, but it's almost always time consuming. Before we can even get to Mecanim, though, we need to get our prototyping model and animations into Unity.

Over the last year, I've purchased a selection of animations from Mixamo that I thought we'd be likely to need for the game. I supplemented those with a few packs bought from the Unity Asset Store. In the future, I'll be buying any stock animations directly from Mixamo. The Mixamo motions in the Asset Store are much cheaper, but you only get the proprietary Mecanim animation file, not the original FBX file, so you can't modify the animations, you can't set curves (which are used to tie the timing of other actions to the animation), and you can't fix mistakes in the motions. 

Unfortunately, the three packs I bought through the Asset Store - the male and female locomotion packs and the prototyping pack, all contained mistakes. In fairness, Mixamo very quickly responded to my feedback. In less than twenty-four hours, they fixed the worst problems - the ones that made the packs unusable. They seem less inclined to fix the more minor issues or to provide some way to use Mechanim curves, so from now on, I'm paying extra for the full motions.

By mixing and matching animations from different packs with the ones bought directly from Mixamo, I should have most of the animations I need to get started with basic character movement. When I discover gaps, I can buy or create animations to fill them.

Rather than test character movement in the prototype level, I'm going to work in a fresh Unity file with a simple map. Once I have the basic movement mechanics working well here, I'll then export the asset over and start testing it in the prototype level. The reason to work in a fresh file is to isolate what's causing problems I encounter. Determining the cause of a problem is much harder if both the map and the character are being constantly changed.

Here's the simple prototyping level I'll be using:
There's not much to it other than a ramp, two sets of stairs, a partial second story, and some room for dropping in objects so we can see how the character interacts with the virtual world.

Because physics calculations can be processor-intensive, game engines usually keep a second set of 3D models in memory that mirror the display model. These collision models (or colliders) are not displayed to the user and are only used for calculating the physical interactions in the virtual game world. These colliders are comprised of lower-resolution models and mathematically defined "primitives" like spheres, cubes, and capsules. These collision models allow the physics engine to provide fairly realistic physical interactions using a smaller amount of processing power than it would take if using the higher-resolution display models.

This is why neither the stock first- or third-person controller provided by Unity is going to work for our game. I want our characters to interact with the world in a believable manner. Both Unity's first- and third-person controllers use a single, large capsule collider to represent the character inside the physics engine. Although the characters look like the 3D model you create, they interact with the world like a giant floating pill.

The green capsule is how your character looks to the physics engine
when using Unity's stock character controllers

For many games, especially first person shooters, this provides a sufficiently believable interaction. It's not going to give the result I want for this game, however. I want interactions with the world to have a higher fidelity than that. Our game is going to rely less on combat and more on stealth and problem solving. Having objects bump away when you get near them, but not move when an extended arm or leg passes through them, is just not going to cut it.

I spent a lot of time trying to modify the stock controllers to give the results I want, but eventually decided I either had to roll my own, or find a third-party controller that works how I want. I found several third-party controllers that were better for my needs than Unity's, but none were perfect, so I'm going to have to build my own.

As I started working on my character controller, I ran into an unexpected limitation of Unity: It lacks support for animated collision meshes. Game models in many engines are comprised of two meshes - a higher resolution mesh that gets displayed to the user and a very low-resolution mesh used for physics calculations. Both meshes are rigged to the model's armature (the virtual skeleton used to animate the model), which allows the physics engine to calculate interactions based on the actual position and pose of the character. By using the animated collision mesh, the engine knows the general shape of the body at any given moment and can calculate physics accordingly.

I built this type of physics mesh for my prototyping character.  In Unity, I added a mesh collider to the character using that lower-fidelity mesh, but then discovered that it didn't animate along with the armature as I expected it to. A little research turned up that this is the documented behavior of Unity. For performance reasons, mesh colliders do not deform with a character's armature.

Needless to say, I was surprised to find out that I couldn't do what I thought was a fairly standard practice. The response from many Unity users in the forums and on Stack Overflow can be paraphrased as "just use the provided controller; it's good enough for us, so it should be good enough for you," which isn't a particularly helpful bit of advice.

I spent a lot of time experimenting, trying to find a way to use an animated collision mesh in Unity. I came up with a way that I thought would let me get around Unity's limitations. Since Unity, Blender, and the FBX file format all allow objects to be parented to individual bones, I thought I could create separate collision objects for different part of the body and achieve the same result as using a mesh that animates along with the character. You can see this attempt below; the collision objects are the orange wireframe shapes surrounding the model. Instead of a single animated collision mesh, I built nineteen separate meshes, each of which moved along with a single parent bone.



I rendered a short animation to see if the physics meshes would animate properly built this way.  Everything seemed to be in line with what I needed.


As I moved over to Unity, things looked good at first. The exported model looked right. All the physics meshes were in the correct places. They weren't physics meshes, though, they were being displayed. That didn't concern me. I just needed to turn off the mesh renderer for them and add a mesh collider to the appropriate bones.

I should've known it wasn't going to be that easy. 

Unity mesh colliders automatically place their mesh so that they take on the parent object's transform (position, scale, rotation). In the case of a bone, that means the collision mesh gets moved to the head of the bone and rotated 90°. All my colliders ended up in the completely wrong place. Here, for example, is where the left thigh collider ended up.



I know how to fix this — I just have to move the origin of each collision object to match its parent bone's transform and then adjust the mesh's shape to overlap the length of the bone. But, I was starting to feel like I was fighting Unity… that I wasn't working with the system the way it was intended to be used.

I went back to researching, and found a few people saying to build your character's collision mesh right in Unity rather than in a modeling program. Primitive colliders like capsule, box, and sphere colliders give much better performance than mesh colliders, even mesh colliders that use low-resolution meshes. Building the collision mesh in Unity is a little tedious, but probably less tedious than fixing the collision mesh in Blender and importing it, and I'll get better performance. I'll lose a little precision, but probably not enough to matter. Most importantly, I won't be fighting my tools.

So, back to Blender I went to re-export the model without its collision meshes. After bringing the updated model back into Unity, I began adding primitive colliders to major bones and ended up with this:


Just like with the earlier model, I wanted to make sure the collision objects moved appropriately when animated, so I made the character dance and filmed it. Yikes. That sounds way creepier typed out than it did in my head.


It looks pretty good, right? But there is a problem with this collision model that's not obvious from the animation above. Everything looks good… until I enable rigid body physics on the character itself. If you look at the green outlined collision objects in the animation above, you'll notice that they overlap at times. The arm, chest, and shoulder collision objects overlap each other, for example, as do the pelvis and thigh objects. Since these are used in physics calculations, this becomes a problem if the parent object (the imported character model) uses physics.

Unity's physics engine is going to try and prevent these meshes from intersecting because it wants to treat them as solid physical objects. That's the whole point of a collision mesh. Unity wants to bounce these off each other. Even if I make all the colliders kinematic (which means they affect other colliders, but don't get moved around by the physics engine themselves), these colliders still cause problems because it will still try to bounce the character off the colliders attached to its bones.

This causes weird, erratic results. I've seen my character start walking on air as if there existed an invisible staircase of randomly sized steps in front of her, I've seen body parts suddenly fly away for no apparent reason, as if they were connected to the body only by a skin of really pliant rubber. 

I could have solved this by leaving large enough gaps between the collision meshes so that they simply never overlap during normal movement. To do that, though, the gaps would have to be large enough that smaller objects in the world could pass through them or, worse, get stuck in them. 

Fortunately, Unity provides two different ways to tell objects not to collide with specific other objects.

The first way is to simply attach a script to objects with colliders that specifies which other objects they shouldn't collide with. Doing that looks something like this:

using UnityEngine;
using System.Collections;

public class IgnoreOtherObject : MonoBehaviour
{
public Collider objectToIgnore;
void Start()
{
Physics.IgnoreCollision(objectToIgnore, collider);
}

}

This solves the problem, but it's tedious, fragile, and a pain in the ass to maintain. There are nineteen collision meshes in this model, each of which is a separate object that has to be told to ignore each of the eighteen other collision objects. Any changes to the collision model means that we'll have to update all the scripts.

There are ways to do this in code that would be less tedious than writing nineteen different scripts, of course. We could, for example, have a single shared script that iterates over all the bones in the character. The script could tell the physics engine to ignore all the other bones that make up the character. That's way better than hardcoding eighteen objects into nineteen different scripts, but it's still a bit tedious because it has to be attached to all of the bones individually. It's also unnecessary.

There's a better way: Unity Layers.

Any object in a scene can be assigned to a layer and the physics engine can be set to have layers interact — or not interact — with any other layer. I created a new layer called Player Collision and assigned all the player character's bones to that layer:



Once they were all assigned to the same layer, turning off collisions between objects on that layer was a simple matter of going into the scene's Physics Settings:


By unchecking the box where the row is Player Collision and the column is also Player Collision, I've effectively told Unity to ignore any collision between two objects that are both assigned to the Player Collision layer, but to continue calculating collisions between those objects and all other objects in the world. In other words, the physics engine ignores when one part of the player collides with another part of the player, which is exactly the behavior we need.

That's enough for today's installment. In the next episode, I'll get our protagonist moving around and interacting with the world.

Next UpPrototyping Player Game Mechanics, Episode II
PreviousThinking About Characters

Thursday, August 15, 2013

Turncoat Dev Diary: Table of Contents

A few people have asked for an index to the Turncoat Dev Diary posts, so here it is. I'll try to keep this updated as I post new entries in the series.

If you're new to these diaries and are not sure where to start, the first one is probably your best bet. Each entry is linked to the next and previous entry, so navigating between them is pretty straightforward.

  1. IntroductionThe Turncoat Dev Diary
  2. Origin of the Universe
  3. Life in the Turncoat Universe
  4. Finding a Smaller Game in the Backstory
  5. Platform Decisions
  6. Deciding on Tools and Frameworks
  7. Just Getting Something Running
  8. Experiments in Environment Creation
  9. Thinking About Characters

Turncoat Dev Diary: Thinking About Characters

(This is part of a series. The first post in the series is here.)

The reason why our original Turncoat concept was going to cost so much to create is that the scope of
the concept was just massive. The squad of soldiers the story follows consists of thirty-four soldiers. They are stationed on an enormous starship with over eight thousand people on board and which is part of a battle group containing about fifty other ships. In addition to the squad, there are many other characters that play into the story, including the Admiral of the fleet and her staff, the ship's captain and bridge crew, the ship's chief medical officer and sick bay staff, the "regular" complement of shipboard marines, and several command officers stationed back at Earth. Then, there's the Seditionists.

There are a lot of fully developed characters required to tell that story and a lot more that would need to be on screen at times in order to make the universe feel as if it was fully populated. On board ships and on an overpopulated planet, space is tight. To convey a proper sense of claustrophobia, we need lots of characters.

Characters are expensive to create.

Characters are also really important to the type of games we want to make. A casual game relies more on the mechanics of the game to generate interest, but a cinematic game puts the story — and thus, the characters — front and center on more equal footing with the gameplay. But, a fully detailed, sculpted, rigged, and facially animatable character like the ones you see in AAA console games might take a single artist a full month to create. We toyed with several ideas for reducing the cost of creating all these characters, such as doing cut scenes with comic-book-like motion graphics instead of fully animated and lip-synched characters and using a lot of close-cropped shots but, in the end, we decided that we couldn't reduce the cost enough without hurting our vision of what the game should be.

When we decided to put the main story on the back burner and start working on the Turncoat Escape game, one of our guiding mandates was to keep the scope of the game down. Way down. That meant having only a single level at first. It also meant keeping the number of characters as small as we could while still making the game work.

That's not an easy mandate to stick to. Stories are about people. If you can get your audience to buy into your characters… to empathize with them and care about what happens to them, you can get those viewers to overlook a lot of other things. But you need that emotional attachment to the characters if your goal is to tell a story.

Or, to put it another way: "It’s the characters, stupid."

There's obviously one character in the Escape game that we just can't do without: the protagonist. The player has to be somebody in the game. There has to be somebody who needs to escape the facility.

In our earliest version of the original Turncoat story, we had one character, nicknamed "Rook", who we envisioned as a customizable character. The player would see events unfolding through this character's eyes, and the player would be able to choose what that character looked like. They could decide what Rook's real name was, whether Rook was male or female, and they could select from a range of skin tones and adjust facial and body proportions and hairstyle.

As the story evolved and grew in complexity, Rook morphed into a specific character with defined traits. I still liked the original idea, but it eventually became clear that the story needed us to know more about Rook.

I like games that let you decide what your character looks like, though. Certainly, there are times when it's important to control the narrative and specify exactly what the main character looks like. Hell, we did exactly that with Rook in order to make our original story work. But, there's also value in making a game welcoming. There's value in telling the player that they can be whoever they want to be in the game, and that whatever they want to be, is okay.

The hero of the story doesn't have to look any certain way.

While we chose to abandon the character customization idea in the larger Turncoat game, the reasons we did that don't apply to the Escape game. This story is less complex. Making the main character customizable won't interfere with our ability to tell the story.

So, that's what we're going to do.

It will add some work for us, which runs contrary to our mandate to keep scope down, but we're still going to do it. It means we need at least two base models for the protagonist - a male and a female - and we need to put some effort into allowing them to be customized. We'll want the player to be able to change the skin tone, body shape, and the facial features in addition to letting them select gender.

So, what other characters do we absolutely need to tell this story? There have to be other people in this facility. Well, I guess there doesn't have to be other people. Through both Portal games, you never see another living person, and that game works extraordinarily well. But we're not making Portal; our story and our game relies on there being more people.

We need guards and inmates. Neither the guards nor the inmates will feature prominently in any cutscenes, so we don't need to make them as detailed as the player model, but we don't want them all to look exactly the same, either. Similar to character customization, we can randomize the features of the guards and inmates to make it feel like there are many different guards and many different inmates in the facility.

We also need a Guard Supervisor. The Guard Supervisor will have a different uniform from the rest of the guards as well as a defined non-random appearance; this character will always look the same every time you play the game. Some of the ways of escaping will require you to either find or avoid the Guard Supervisor, who is more observant and generally more competent than the regular guards.

Finally, we have the "white coats". The white coats are not part of the regular game level. They're never in the cell block or the guard areas. They're only inside "the theater" - that part of the map that the player can see from some of the ventilation ducts, but can't directly interact with. Exactly what it is that the white coats are doing in this facility is one of the things the player will be able to discover if they explore. They won't need to know that information in order to escape, but they'll have a better understanding of why they need to escape and why they're in the facility in the first place if they do.

One thought I had for the white coats was that since the vents are mostly down low at floor level, we might be able to make it so you simply never see their faces. As long as the the characters aren't too far away from the vent, the angle should hide their face from view. This might add to the mystery of these characters, and will have the added bonus that we won't have to fully model or animate the white coats' faces. That should reduce the amount of modeling effort.

So, our tentative list of characters right now is:
  • Configurable female protagonist
  • Configurable male protagonist
  • Randomizable female guard
  • Randomizable male guard
  • Guard Supervisor
  • Randomizable female inmate
  • Randomizable male inmate
  • White Coat Male (no face rigging)
  • White Coat Female (no face rigging)
That seems doable. It's, perhaps, a little longer of a list than would be idea, but as long as we don't go too crazy with the ability to customize / randomize, we should be okay, especially if we try to reüse parts, like faces and hands, between the guards, inmates, and white coats.

While we're going to create some of the characters in-house, I think we've probably got more characters than we can do without some outside help, so if you know any good character modelers with game experience looking for a little freelance work, have them drop me a line at jeff at martiancraft dot com.

Next Up: Prototyping Basic Game Mechanics Part 1
PreviousExperiments in Environment Creation

Monday, August 12, 2013

Turncoat Dev Diary: Experiments in Environment Creation

(This is part of a series. The first post in the series is here.)

Today, I'm going to talk about a little side quest I took while prototyping the game: painting and lighting one of the rooms. When I initially planned the level out in Blender, I did it almost entirely with cubes. I scaled and extruded and adjusted vertices, of course, but when you come down to it, it really was just a bunch of boxes. Of course, a lot of buildings in real life are just assemblages of boxes if you look at them from far enough away, but to try and make an environment that feels real, I knew I needed more than just boxes.

I selected one of the smaller room to paint up - a sort of locker / shower room part of the intake processing area. I chose it because it's small and because I should be able to texture it quickly using readily available stock textures. While the game is going to be set in the future, I want to base the look of it on the real world, so I started looking for reference images as well as tileable images suited to how I was picturing this room in my head. It's funny the kind of little details you don't really notice until you try to recreate something, though. In most cases, for example, doors just don't look right without some kind of molding or frame. It took me surprisingly long to figure out what it was about the doors in my prototype that bothered me. Just cutting a hole in a wall is perfectly functional, but it doesn't feel right because in the real world, doors almost always have a visible frame around them.

Another thing I noticed is that when you start looking closely, even at a relatively clean environment, there are marks, scuffs, and smudges on nearly everything. They're often subtle, but they're almost always there. Now, a lot of that subtle smudge detail in a normal room would fall below the fidelity of the medium, but in this case, I want to exaggerate it and make everything extra grimy. I want to convey not just that this is a depressing, unfortunate place to be, but I almost want a sense of neglect and even foreboding. I want it to feel like the people running the facility don't care about this particular place or the people it contains. Even before props or characters are added or dialogue is recorded, I want this level to convey a sense of desolation. Things are dark, dirty, and just generally unpleasant. This is an out-and-out bad place; escape is imperative.

After spending a few hours with Google's image search looking for inspiration and reference, I started adding some details to the cubes that made up the room I had chosen to paint. I cut out a window between the two rooms, added moldings to the doors and window. I cut out drains in the floor of the shower area and cut vents in the wall. I added planes to hold some signage and also for the ceiling lights.
I really don't know how much of this detail will survive through to the final version of the game, and it really doesn't matter. The goal here is to explore the process and to try and get a feel for whether I need to bring in a dedicated environment artist. If the actual work gets thrown out, that's okay. That's the nature of prototyping.

Once I had the details modeled, I started mapping textures from CGTextures, the Blender Texture CD, and a few other source onto the room's surfaces. I did this to give me a starting point. It's easier to work from something rather than painting on a completely blank canvas. 

Once I had all the surfaces mapped to textures, I "baked" them to a fresh texture map. Baking the textures to a single image will allow me to paint right on the 3D model directly using Blender's paint tools. Here is a reduced size version of the baked map for the shower room (left), along with how the room looks in paint mode in Blender (right):


It's certainly more realistic than my earlier white-walled prototype. Firing up Unity, this is what it looks like now:


It's definitely better, but it still falls way short of feeling real and it's way too clean and bright. On top of that, the current lighting just makes no sense. There's no visible light source, but the room is lit as if there was a light floating in the middle of the room. I'll fix the lighting later, but first, I want to work on the textures.

I went back to blender and started to filthy the place up. The grime will help make the room feel decrepit and it will also break up the repeating patterns from the tiled images I used, making it harder for the eye to pull them out. I loaded up an assortment of dirt, grime, and grunge images to use as brushes and started painting on the room's textures. It's a little weird painting on the inside of an object. Blender's Texture Paint mode works like Unity in that you can only see the "front" of polygons which, in this case, means the inside. Like one of those optical illusions, my eye wanted to think the texture was on the outside rather than the inside, but after a few minutes, I adjusted and work started going faster.

Doing something like this really makes you appreciate the power of undo.  I hit ⌘Z a lot while working on this, and it took me a long time to find an approach that gave results I liked. 

Once I had the new details and grime added to the texture, I pulled the new maps over to Unity to try them out. I also tweaked the shaders a bit, adding a distortion map to the window and creating normal maps for the tiles to give them a tiny bit of depth.


It's definitely an improvement. I might've been a little heavy handed with the grime, but I want to wait until I've done some work on the lighting to decide whether I should pull back on it. I envision this area being much darker and poorly lit than it is now, so I want to judge the texture in the correct lighting. 

In addition to being darker, I also want some of the lights to be flickering or burnt out. A little googling around found me a great light flickering script that gives just the effect I want. In Unity, I started placing lights around the room. Each of the two sections of the room has four light fixtures, but I decided that each section would have one light that was burnt out. The shower room would additionally have a flickering light and an an illuminated exit sign.

In order to keep performance reasonable with so many lights, I decided to bake light maps for the lights except for the one that flickers. "Baking" a light map essentially creates a texture map to store pre-calculated lighting information. They let you do lighting effects that are normally too processor intensive for real time calculation. The downside is that baked lights don't cast shadows on dynamic objects (like the player, moveable props, or bad guys). For a desktop computer or console version of the game, we'll probably want to make more of the lights real-time to get realistic shadows, but for mobile, we really have to be careful to limit the number of dynamic lights to keep the framerate up.

The Beast Lightmapper that's built into Unity is quite good and not that hard to learn, but calculating lightmaps is a fairly processor intensive task. Getting all the lights configured the way I wanted ended up taking a long time. I'd tweak one or two settings, then re-bake and wait five minutes or so. Lather, rinse, repeat.

After a while, I got the light maps baked mostly to my satisfaction. I started liking the overall look much better. The grime, which was kind of overpowering in the brightly lit room, feels just about right now. It still could use some furniture and other props, and the overhead lights could use some more detail, but on the whole, it's not terrible.


I wanted the shower room to be even less well-lit than the outer room, possibly to be used as a hiding place in the final game. This is how it looks after re-doing the lighting and baking the light maps:


It's not perfect by any stretch of the imagination, but the overall effect is roughly in line with what I want to achieve for the final game, and it only took me two days of experimenting to get to this result.

Here's a short video if you want to see it in motion.


At this point, I've done enough to believe we can do the environment work in-house. I understand the technical process well enough, so if I team up with one of our designers who has a better aesthetic sense than I do, I think I can get an environment that looks the way I want it to look.

Well, enough of this side quest. I think it's time to return to prototyping. Before that, however, I want to talk a little about the game's characters.

Friday, August 9, 2013

Turncoat Dev Diary: Just Getting Something Running

(This is part of a series. The first post in the series is here.)

Once I had made the list of tasks that had to be accomplished in order to get the game created, my brain started going in a lot of different directions all at once. I kept flitting between thinking about different tasks, trying to judge whether I could do the task, one of our existing MartianCraft developers or designers could do it, or if I'd need to go out-of-house to get it done at the level of quality and finish I wanted. A few items, like sound effects and music, I felt comfortable pushing to the back burner for now, but I felt a need to do an informal triage of many of the tasks. Some of them would require finding either freelancers or new hires and that adds time. I wanted at least some idea of what kind of outside talent I would need.

After about a half day of bouncing between the various tasks and just generally being a disorganized mess, I realized I was putting the cart in front of the horse. I need to just get something running to make sure the core idea was even worth pursuing. The greatest art and sound can't rescue a game that's not enjoyable. So, I pushed aside all my other concerns and thoughts to try and get a simple prototype up and running.

Fortunately, with Unity, that can be done pretty quickly. It took me less than day to get a prototype level built so that I could navigate it. Today's dev diary is about that process.

Unity doesn't have a level editor, per se. It has a scene editor with some basic primitives and some really good terrain tools. Levels are generally built in the scene editor using components built in an external 3D program, unless it's an outdoor environment, in which case you can often do everything right in Unity.

From the time I first thought of the escape game concept, I had some idea of how I thought the level should look and about it's overall layout. Now, that layout wasn't really driven by gameplay concerns, but rather by storytelling concerns. I had certain information I wanted to get to the player and some information that I wanted to make available to more adventurous players who explored beyond what was strictly necessary to escape. I envisioned the basic map as looking something like this:
The black area I envisioned as a somewhat standard prison cell block, although probably a little more futuristic looking than a prison you might find today, and the light blue boxes I thought of as solitary confinement cells, some of which would be used as starting points for the level. The darker blue areas would be administrative areas: the guard break room and the supervisor office. Marked in red is a series of ducts that can be used by some characters (those who aren't too big) to hide from guards and navigate around the map where the guards can't see them. The green area I think of as "the theater." The ventilation grates in those rooms don't open and the player can't actually go into them, but if you they are in the ducts and get close to the grates in any of those rooms, it will trigger in-game animation sequences (and not necessarily always the same one). These sequences will hint at additional ways of escaping the level and also fill in more background information about the universe and why the character has been imprisoned.

The goal of the game is to get to the security elevator, which is outlined in gold. It looks like a straight shot up the center from the isolation cells — and it is — but that hallway is well lit and well guarded. Plus, you can never go directly to the elevator. You always have to do something first before you can go there. You might have to disable a force field, find a key, or restore power to the elevator before going to it makes any sense. Once you've done that, then you need to get past the various guards without being detected in order to escape.

Once I saw the map laid out, I realized it wasn't enough. There needed to be more than one way to get to the elevator so that we could give the game some amount of replayability and also give the player more stuff to explore. I felt that there needed to be more rooms outside of the main prison block to give the player places to hide and explore.

I came up with the idea of adding on an "Intake Processing Center". The existing entrance to the elevator would be the one that guards and other staff used, but new inmates would come in a different way. They would come in through a series of rooms where their belongings were stored, mugshots were taken, and prison clothes were issued. I added on a series of rooms to the map for this purpose, as can be seen in purple below.
I originally started trying to draw out the level map old-school style. But, it wasn't really working for me. It was keeping me from thinking in three dimensions. So, I fired up Blender and started planning the map in 3D. The maps above are actually screenshots of the top orthographic view in Blender that I added some color to using Photoshop.  As you can see, it's actually a three dimensional map:
Working in 3D seemed to make sense, since the file I created can be exported right to Unity for prototyping. At least, it can if I built it right. There was only one way to find that out, though: export it from Blender and import it into Unity to try it out.

My first attempt didn't work out very well. I dropped a First Person Controller (something provided by Unity for creating first person games) onto my map so that I'd be able to navigate around the map. For the final game, I won't be able to use the provided Unity component, but it will work plenty well for letting me look around my map. 

I hit play, and saw… nothing.

Oh, right. Lights! The "real" lighting for the game will be done much later in the process, but I needed some light to see anything. I could've just turned on global ambient lighting, but that wouldn't give any shadows to judge shapes or distances. Instead, I dropped a somewhat random assortment of real time point lights onto the map. Performance won't be good, but at least I'll be able to see well enough to navigate the map. Since I'm using my dev machine to navigate around the prototype level right now, I'm not overly concerned about performance issues yet.

Once I had the lights added, I hit play again. And saw… nothing. Again.

Then I swore at my computer.

Fortunately, I realized what the problem was before the swear words were even completely out of my mouth.  Blender (and, I'd imagine, most 3D programs) assume that objects are going to be viewed from the outside, not from the inside. While Blender supports two-sided polygons, Unity doesn't, so when designing interior architecture, you have to make sure your objects are built, essentially, inside out - with the face normals — which mark the forward or visible direction of the polygon — pointing inwards.

You can see in the Blender screenshot below that the normals (the light blue lines) are facing outward. Most 3D objects get created this way so they can be seen from the outside when you're using one sided polygons.

Outwards, in our case, is bad. Outward pointing normals mean you can see this room from the outside, but not when you're standing inside of it. Fixing it was a simple matter of selecting each room in Blender, going into Edit mode, selecting all faces and then hitting the "Normals / Flip Direction" button in the left toolbar.


Once I fixed the normals, I re-exported, went back into Unity, waited for the level to re-import, then hit play. This time, I actually got something:


Well, yay! I've got a map and I can even walk around the level. I haven't written any code yet, but I can actually navigate from the user's perspective and get a feel for the level. I'm really liking my decision not to try and write my own game engine right now.

I found it kind of hard to maneuver, though. It is soooo white in here that it's hard for the eye to grab onto anything, especially when you're not near a point light. Even for a throwaway prototype, I needed some textures for the eye to grab onto, so I pulled down a few tileable images from CGTexture

Using repeating textures won't cut it for the final game. That was the state of the art a decade or two ago, but not today. The human eye is just too damn good at picking out patterns for us to rely on repeating images for very much. But, for testing, getting any kind of texture on the floor and ceiling was going to make a big difference. I also made the cells a different color than the hallways, which helped quite a bit as well.


It's not going to win any awards for level design or aesthetics, but it's a starting point. I can walk around, find the more glaring problems, and get a feel for how the layout will work. The first thing I did was to make sure I could get everywhere I wanted the player to be able to go. I found a few mistakes along the way - polygons that should've been deleted to make doors and normals that didn't get flipped. I also found a few gaps between rooms that were noticeable. Those were all pretty easy to fix in Blender, which I did.

The one thing that did strike me, as I walked around the map, was that the level is too small. Probably a lot too small. At a walking speed that feels natural, you can navigate the entire map fairly quickly. Even accounting for the fact that you'll be sneaking and avoiding guards much of the time, it's still too small. I'll have to go in later and make it bigger. But this is enough for an early prototype - to test out game mechanics and bad guy AI.

Now, if I were focused, this is the point where I would start working on some actual game mechanics. I'd drop in a few bad guys with simple AI so I could start actually playing the prototype and figuring out what works, if anything. But, I'm not focused. I'm the kind of person who…

Ooh, look! A shiny object…

What was I saying? Something something, focused… oh, right. There are some tasks that I know we're going to have to go out of house for, and some that I know we can do in-house. Then, there are the ones that I'm just not sure about yet. One task that I think we can handle in-house with existing talent, but don't know for sure, is painting and lighting the environment. So, I allowed myself to be distracted from the prototype to do a quick paint-up of one room on the level. That room will probably need to get re-done at least once before we ship, but it seemed a worthy experiment and something that would be kind of fun. Plus, it would help me get familiar with some Unity functionality that I've not used before (light maps), some new 3D painting improvements in the latest version of Blender, and it will just generally help with the decisions that need to be made about the overall aesthetic feel of the game. I'm a visual person and sometimes need to see something to know if I like them, because they always look good in my imagination.