Tuesday, September 24, 2013

Turncoat Dev Diary: Visual Design Begins

We're starting to narrow in on our first game after putting the stealth game on the back burner. I'll be ready to share more about that in the next week or so. Today's post, though, is not about game mechanics, it's about the look and feel.

We've brought two excellent visual artists — Patrick and Alex — on board to help establish the visual style of our game universe and the first game.

You can check out Patrick's work at his Tumblr and on his blog. You can also follow him on Twitter… um… if you dare.

You can see some of Alex's stuff on his blog and follow him on Twitter.

I'm really excited to be working with these guys and can't wait to share some of the stuff they create.

In one of my next few posts, I'll talk about the mechanics of our first game, but for now, I'll just say that guns — and especially scoped rifles — are an important element of the game, so one of the first things I wanted to explore was what those guns might look like in the 24th century.

The process started with silhouettes. Alex came up with a sheet of different gun outlines based on both historical and modern weapons as well as taking inspiration from a variety of fictional sources. Here is a low-res version of the first silhouette sheet:



Talk about decision paralysis. So many cool looking guns silhouettes!

While we'll have multiple guns in the game when it ships and we'll eventually explore several of these designs, we have to start with one. Picking just one wasn't easy, though. Instead of deciding based on aesthetics, I decided to look at function. Our protagonist needs to start with a gun, but we don't want them to start with the coolest, fanciest, or biggest gun. Rather, we want them to start with something practical and multi-purpose. Both J & K looked to me like assault rifles that have been modified for sniping, and that feels like a good starting point for the default weapon. It's the weapon of a newly-qual'd sniper deployed with his or her squad.

So, Alex is now working on variations of J & K to come up with the design of the first gun our players will use. We'll be exploring some of the other silhouettes later and evolving those into finalized designs as well.

While Alex is exploring guns, Patrick has been exploring environments. The logical starting point for him was to create a rifle range for practice and training levels. We don't want players to worry about enemies shooting back at them until they've had a chance to at least try out their gun against inanimate objects, so Patrick is working on figuring out just what the rifle range on a 24th century spaceship might look like. None of the environment stuff is far enough along to share yet, but I'm looking forward to when we can.

Tuesday, September 17, 2013

Turncoat Dev Diary: Touch Controls are Hard… Let's go Shopping!

I haven't been making my "every week" blog post commitment for the last couple weeks. I apologize for that. There are few reasons on top of the ordinary work life busy-ness that have caused it.

First… well, touch controls are hard. I've got a partially written post exploring the use of touch controls for stealth games, but I haven't been able to hone in on something I'm 100% happy with. I've got something that I like better than any stealth-based iOS game I've found, but it's still nowhere near being shipworthy. Part of that is because this type of game grew up in the console world, where you have controllers like this:


Have you ever thought about the sheer amount of input that you can take through one of these modern joysticks?  The Xbox 360 controller, for example, has two analog joysticks, each of which allows analog input on two separate axes. That's four inputs that accept a range of values each, letting you (for example) not just specify that you want to move forward, but to actually specify the speed at which you want to move.

But there's actually another two analog controls on top of those. The left and right triggers are not buttons, they're also analog controls with one axis each. The harder you press them, the higher the value received. The DPad is the equivalent of eight tac buttons. There are four standard buttons (A,B,X,Y) and two shoulder buttons (RB, LB). Even without counting the start, Xbox, and back buttons, and without using combinations of buttons, we're talking about 14 buttons and 6 analog axes. Oh, but wait… each of the analog sticks can be pressed down and used as a button, so it's 16 buttons and 6 analog axes. If you count all the buttons, it's 19 buttons and 6 axes. You can also chord the A/X, A/B, X/Y, and B/Y buttons, allowing the equivalent of an additional four inputs.

That's an awful lot of input. These controllers are well designed, so you don't think about just how much data you're able to submit to a game using them, but as a game designer, it's something you have to think about.

If you look at the most successful and popular iOS games, they're not (generally speaking) copies of console games. There are exceptions, of course, like the recent Deus Ex game but, frankly, that one got by on its production value and franchise nostalgia. The controls are actually quite frustrating. A sloppy combination of direct manipulation, virtual joystick, and on-screen buttons that's hard to learn and hard to use.

I still believe that there's a way to do a stealth game on a touchscreen well without using an external controller, but I haven't found it yet. I think I'm going to put this idea on a back burner and return to it in a little while, maybe for the second or third game in the series. 

Another reason I haven't blogged recently is because I've been busy recruiting some pretty amazing artists to work on Turncoat. Pretty soon, I should be able to start posting some concept art and pictures of game assets. I'll tell you more about these artists in a future post but, for now, I will say that I'm super excited to be working with them and I can't wait to start showing you some of the art they create for the game.

So, where are we going from here? Well, we're probably going to be focusing on some high level look-and-feel stuff for the next few weeks and are also going to explore alternate game mechanics for the first game. It's important to me that the first game be really solid and also that it be produced in a timely manner. I just don't think that's going to happen with our original concept.

I'm also thinking about getting away from the prequel idea. There's something in the backstory that I was going to have to reveal if we kept going the prequel game as originally imagined, and it's something I really don't want to reveal yet for a couple of reasons. Instead, I'm thinking about focusing on origin stories for the main members of the squad. Everybody who gets recruited into The Squad, did something to get noticed. Some act of heroism, selflessness, or brilliance that caused the Squad's Commander to recruit them.

So, instead of going a hundred years in the past, we're going to only go back 2-5 years. We're in the same universe, dealing with a lot of the same characters, but they're not on The Squad yet. These will be fairly self-contained stories that can be told without having to reveal any of the secrets of the universe.

At this point, I know which character's origin story we're going to do first, but I don't know for sure the game mechanics that will be used to tell that story. I've got some ideas that I'm going to explore, though, so look for future posts.

Wednesday, September 4, 2013

Turncoat Dev Diary: Help! I'm Falling and I Can't Stand Up…

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

Just as I started trying to figure out how the game's touch controls should work, I  began to be really bothered by a couple of problems in the basic movement of my character. One of those things, I've mentioned before, is the funky camera accordioning in the arc right and arc left animations. Turns out, those issues were more than cosmetic; the stuttering camera combined with the fact that stopping isn't instantaneous made it virtually impossible to line up the character precisely as you stopped moving.

It was easy enough to solve, though. I simply removed the arc left and right animations from the blend trees in my state machine, then added some code to my character controller class to simply rotate the whole character as she walked:

    transform.Rotate(0, horizontal * turnSpeed * Time.deltaTime, 0);

The turnSpeed variable can be set in the inspector, so it can be adjusted on a per-character basis. The horizontal value is pulled from the x-axis of the joystick or determined from the left/right buttons or touch screen controls. The resulting turn animation is a tiny bit less realistic than using the animated left and right turns. You'd think that just rotating the whole character a small amount while they walked forward would look really fake, but it doesn't. Maybe it's simply the fact that this is the way most third person games ever created, including pretty much every MMORPG, have worked. Maybe our eyes are just accustomed to this particular cheat. Either way, I'm willing to sacrifice that tiny bit of realism for better, more precise controls.



After playing with it a bit, I decided that turn speed probably shouldn't usually be the same when walking and running. Instead of just setting a single turn speed in the inspector, I'll let you set both a walk and run speed and then interpolate between them. They can be set the same using this approach, but they don't have to be.

float turnSpeed = (turnSpeedDifference * currentRun) + walkingTurnSpeed;
transform.Rotate(0, horizontal * turnSpeed * Time.deltaTime, 0);

The variable turnSpeedDifference gets calculated once at startup, since I don't anticipate these values changing at runtime:

turnSpeedDifference = runningTurnSpeed - walkingTurnSpeed;

I'm pretty happy with turning now, but there's another problem that I didn't notice until I expanded the playing field. The original field was sufficient for testing the basics of movement, but I realized that once I moved beyond the basics, I'd need ways to test things like crawling through vents and taking cover, so I expanded the test field, making it taller and longer. I added some ducts the same size as the ones in the prototype level, added some objects to take cover against, and added a third level platform and another set of stairs. That made the test level look like this:


As I started exploring this expanded test level, I realized that falling from a distance greater than, maybe the equivalent of two to three meters, looked unnatural because my character would try to  walk or idle. Walking on air is a pretty neat trick, but not very realistic.

The provided CharacterController class, which is what I've been using to handle basic interaction with the environment (climbing stairs, being affected by gravity) has a method called IsGrounded()¹ that will tell you if if you're standing on the ground. If you're walking, running, or idling, this will return true. If you're jumping or falling, it will return false.

That's the theory, at least. It always returns true for me no matter what my character is doing. Now, I understand why it might not work when jumping because the elevation increase is baked into my jump animation - the character controller doesn't actually leave the ground. The bone colliders move up into the air, so interaction with props is correct, but the implicit collider used for interacting with terrain does not. As a result, IsGrounded() is returning true. More confusing to me, though, was why it's returning true when I fall off of one of the higher levels. I had no working theories about why it wasn't working as expected. Even when falling off a third story platform, it would never report false for IsGrounded().

Because CharacterController is an opaque class provided by Unity, there wasn't an easy way to debug why it wasn't working as expected, so I decided to stop using the provided class and roll its functionality into my own controller. I removed the CharacterController component and added a RigidBody component (the component in Unity that makes something part of the physics world) as well as a CapsuleCollider. Because my character is part of the layer Player Controller, just like CharacterController used to be, CapsuleCollider should only interact with terrain, not with props, which will be left to the bone colliders. In theory, everything should work just like before except for situations that were being explicitly handled by the CharacterController class.

Surprisingly, the swap worked really well. It works way better than I expected, actually. Without implementing the IsGrounded() functionality, I'm already able to move around the level just as I was before. I had to tweak various values on the RigidBody and CapsuleCollider components to get things just right, but it turns out I was getting far less benefit from the CharacterController component than I realized. Even climbing up slopes and stairs works pretty much as expected.

Pleasant surprises like this one are few and far between. I expected to put a lot more work into replicating the functionality I was getting from CharacterController, so I took a moment to savor the victory.

Then it was time to turn my attention to figuring out when my character is grounded, when they're jumping, and when they're falling so that I can show the correct animation for each situation.

I tacked whether they're grounded first. There's a couple of different possible approaches here. The one I opted for is to simply cast a ray straight down from the player to determine the distance to the ground. If that distance is greater than what it is when they're just standing, we know the character is not grounded. In my case, that looks a bit like this:

        RaycastHit groundHit;
Physics.Raycast (origin, transform.up * -1, out groundHit, 100f, groundLayers);
grounded = groundHit.distance - groundedDistance <= 0f;

The variable origin is the calculated center of the capsule collider. The second parameter to Physics.Raycast is the direction I want the ray cast in, which is straight down. If we multiply transform.up by -1, we get a vector pointing straight down from the character. I don't know why Unity provides a method to give you a vector pointing up, but not one for pointing down, but multiplying the up vector by -1 gives us a down vector.

The third parameter is used to determine what object was hit, if any. C#, like Java, doesn't have pointers, so that funny out keyword is used to pass groundHit by reference rather than by value. As I've said before, I don't hate C# nearly as much as I hate Java, but there are still times when this language bugs me. Here's one example. I miss pointers. I know many devs feel we've outgrown the need for pointers and that our languages should hide them from us but, personally, I find this whole out² business to be far clunkier than simply passing the address of a variable. I understand some of the security concerns around pointers, but all the other arguments against them ring hollow to me.

Anyway, the next argument (100f) simply tells the ray cast to stop looking if it hasn't found something within 100 units. In my test level, units are roughly equivalent to meters, so that should be far enough to hit the ground no matter where I am on the level. The final argument is called groundLayers, and this one's a little confusing.  This is a bitwise mask field used to specify which layers I want it to look for when ray casting. It's very similar to the physics settings I used previously to keep the bone colliders and character collider from interfering with each other.

Determining which values correspond to which layers is a little confusing but, fortunately, you don't need to. You can declare a public LayerMask variable, and Unity will present a user interface in the inspector to let you select the layers to be included.


Once I have the results of my ray cast, it's relatively easy to figure out if I'm grounded. The variable groundedDistance is half the height of the capsule collider plus a small amount extra to account for small terrain changes. I'm ray casting from the center of the collider, so the ground should be half the collider's height away. If it's further than that distance (plus a little slop), we're not grounded.

In my testing, this works perfectly, except the jump problem is still there. My capsule collider doesn't move up as the character jumps, so this code reports that we're grounded when we're jumping.

For the jump problem, all I have to do is add a boolean variable to the class to track when a jump starts, and when it ends. Only, it's not quite that simple. When you tap the jump button, that starts the jump animation. With a running jump, the character immediately springs into the air, but with a standing jump, there's a build up as the character bends their knees down and then springs up. In both instances, the character's feet hits the ground some time before the animation ends. It seems like that's the point where we want them to start falling. We don't want them to land on thin air and then start to fall down.

The first thing to do was to figure out the exact timings for my two jump situations. After some trial and error, I came up with these values:


    // Timings used on the jump. Running jump starts immediately and transitions immediately back
private static float jumpResetDelay = .1f; // Used to set the Jump input back to 0
private static float runningJumpAnimationDuration = .416667f; // Running jump animation is reported as .867f seconds,
// but is actually .416667, Mixamo probably trimmed on import

// Standing jump has a build up and recover, so feet don't leave the ground immediately, and animation continues
// for a short period of time after
private static float standingJumpLeavesGround = .5f; // When the feet leave the ground on standing jump
private static float standingJumpBackOnGround = 1.2f;

Now, the trick is to use them. This is one of those areas where language differences bite you. Pretty much every mechanism that I would use to accomplish this in Objective-C or C aren't available in Unity using C#. Apparently, for performance reasons, Unity's APIs are not threadsafe. Even though C# supports threading, Unity kinda doesn't. Instead, the suggested way to do something like this is to use these funky things called co-routines, which are functions that yield execution back to the calling thread. In Unity, these functions will fire on the main thread, but they can yield time back to the main thread, similar to a thread sleeping for a specified period of time.

After some playing around, I cam up with something that seems to work well. When the jump button is tapped, this co-routine fires:

IEnumerator TriggerJump(bool isRunning)
{
if (isRunning)
{
jumping = true;
AnimatorSetJump(true);
yield return new WaitForSeconds(jumpResetDelay);
AnimatorSetJump(false);
yield return new WaitForSeconds(runningJumpAnimationDuration - jumpResetDelay);
}

else
{ AnimatorSetJump(true);
yield return new WaitForSeconds(standingJumpLeavesGround);
jumping = true;
yield return new WaitForSeconds(jumpResetDelay);
AnimatorSetJump(false);
yield return new WaitForSeconds(standingJumpBackOnGround - (standingJumpLeavesGround + jumpResetDelay));
}


jumping = false;
}


If the character is doing a running jump, the public variable jumping gets set to true immediately, but if they're doing a standing jump, then we wait until the character's feet actually leave the ground to set it. In both cases, we set the Jump input to the animation state engine back to false after a short delay to make sure we don't accidentally trigger a second jump animation, and then, when the character's feet are back on the ground, we set jumping back to false.

Back in our Update() method, we should not be able to check at any point to see if our character is jumping or not and get the correct value (though some tweaks to the timing are to be expected during testing). Knowing this will help us avoid falling into gaps that we're trying to jump over, for example. Now that I can tell when we're jumping, I can update the grounded check to take jumping into account.

    Vector3 origin = transform.position + transform.up * movementCollider.center.y;

RaycastHit groundHit;
Physics.Raycast (origin, transform.up * -1, out groundHit, 100f, groundLayers);
grounded = groundHit.distance - groundedDistance >= 0f && !jumping;

Now that I have a reasonably accurate way to determine if the character is grounded, I should be able to tell when to fall and when to stop falling, right?

*sigh*

I knew I'd pay for that earlier bit of serendipity. Turns out, the whole falling thing is a harder than I expected. I implemented the code to start falling when the ground is a certain distance away. I made that distance configurable, since it could conceivably change based on the character's height, and then set it for this character. It mostly worked. There are some edge cases, such as when going up stairs fast, where it needs to be tweaked but, for the most part starting a fall works as expected.

Landing, however… Well, landing doesn't work so well. The character "lands" a few feet above the ground and then settles down to the ground as they start to stand up.

This one made me pull my hair out. It made no sense to me.

It wasn't until I watched the character in Unity's scene view that I realized what was happening. The character's height changes as they fall, and then again as they absorb the impact of the fall, but the capsule collider being used to figure out when they've hit the ground doesn't change in height, so we detect hitting the ground while our character's feet are still a few feet above the ground.

That might make more sense if you see it in action:


You can see how significant the difference in height is in this screenshot:


There's a couple of ways I can fix this. The way that the Unity Mecanim tutorials show is to use an animation curve and tie the height of the capsule collider to that curve.

We do need to make the capsule smaller and adjust its origin up a little so it overlaps our character while falling but, in addition to that, we're raycasting from the center of the capsule in code to figure out if we're grounded, so we have to account for this change in height in that code as well. Since I have to write code to deal with this, I think I'd rather handle the capsule collider changes there as well. By saying that, I probably sound to the Unity folks the way people who refuse to use Interface Builder sound to us old school Mac and iOS devs, but it seems logical to keep the functionality in one place.

With some trial and error, I found the right values and timings for resizing the collider. Those will likely need some tweaking as I test more, but I'm pretty happy with the overall result. I was just about ready to move back to figuring out touch controls when I started noticing another movement problem. When I ran up stairs or up the slope, it would sometimes start falling at the top, even though there wasn't any way they could possibly fall there.

Ray casting doesn't take into effect the size of the collider, it just draws a line straight down from specified point. There's a small gap between the top stair and the platform. It's tiny - not big enough for a person (or our collider) to fall through, but if the ray cast happens to be exactly over that gap when I do my check for falling, we get a false positive for needing to fall, and the wrong animation gets kicked off.

I could cast multiple rays down to make sure the gap isn't too small to fall through, but Unity actually provides a way to do a ray cast that takes X and Z size into account. It's called a Sphere Cast, and I stumbled upon it purely by accident.  Fixing this issue turned out to be a matter of simply changing my ray cast cal to a sphere cast call, using the radius from the capsule collider

    RaycastHit groundHit;
//Physics.Raycast (origin, transform.up * -1, out groundHit, 100f, groundLayers);
Physics.SphereCast(origin, movementCollider.radius, transform.up * -1, out groundHit, 100f, groundLayers);
grounded = groundHit.distance - groundedDistance <= 0f && !jumping;

At this point, basic movement is working pretty well. I can walk, run, jump, and fall down fairly realistically. I still have to do crouch and and cover, but with these fixes, I think I'm finally ready to start exploring touch controls.

Next: Touch Controls
PreviousPrototyping Player Game Mechanics, Episode II



1: Yes, this is correct. The accepted convention in C# for naming methods is to start them with a capital letter. Considering this language came from the same people who gave us Hungarian Notation, however, this is a pretty tolerable bit of ugliness.

2: It seems simple, right? Specify out if you want to pass by reference, leave the keyword out if not. Only, it's not quite that simple. You can also use the keyword ref to specify you want an argument passed by reference. Two ways and both that do the same thing but if you use ref, the variable has to  initialized before it can be passed in. With out, the variable doesn't need to be initialized. This isn't simplicity, it's just different complexity with less power.

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