Showing posts with label Dev Diary. Show all posts
Showing posts with label Dev Diary. Show all posts

Saturday, October 12, 2013

Turncoat Dev Diary: Going Ballistic

We're still working on getting our ducks in a row administratively so we can actually announce the name and basic details of our first game, but as I've mentioned before, it is going to be centered around the use of guns. The Turncoat universe is set four hundred years in the future, so there will be fancy futuristic weapons available, but I wanted the first weapons you get access to in the game to be essentially more advanced variants of modern ballistic firearms.

You could argue that by the year 2400, cartridge-based combustion-propelled firearms will be horribly obsolete. Certainly many fictional futures have taken that route and opted for only rays guns, lasers, blasters, phasers, ion cannons, and other such options.

But, if you think about it, the sophisticated modern firearms of today are based on the exact same principles as weapons created in the fourteenth century. Using combustion to propel a small piece of metal very, very fast has proven to be a very effective way to harm living things. Firearms have been around for seven hundred years without becoming obsolete, so there's no reason why they wouldn't still be in use in some form four hundred years from now alongside whatever other new ways of killing get created.

When it comes down to it, however, it really doesn't matter how likely anything is in reality. From a gameplay perspective, we want to have many options for our players. We want them to be able to use different kinds of guns with different gameplay characteristics and to be able to upgrade those guns in numerous ways. Our goal is to add variety to the experience of playing the game, not accurately predict the future of weaponry.

As I started prototyping the gun mechanics in code, I found a lot of examples and tutorials scattered around the Internet about how to do guns in Unity. Most of those tutorials recommended a simple raycast (combined, of course, with sound and visual effects). You cast a ray out from the gun's barrel and see if it collides with something. If it does, you have a hit and the result of that hit happens immediately. And why not? As far as human senses are concerned, bullets from modern guns might as well be instantaneous except at the very longest range of the most powerful sniper rifles.

But that approach is no good for our game. One of the main benefits of the later advanced weapons in the game is that they don't suffer from some of the problems that ballistic firearms have. For example, when shooting at long range with a sniper rifle, you have to account for the trajectory of a bullet, the fact that gravity pulls the bullet downward as it moves forward, and the fact that other forces, like wind, can act on the bullet. Ray guns don't have that problem. They're simply point and shoot, so to speak, and raycasting makes perfect sense for those later, more advanced weapons. But raycasting doesn't take the realities of a physical world into account for a ballistic firearm.

I want the firearms in the game to "feel" real, and I want the bullets to behave the way a real bullet would. I'm all for cheating when it makes for a better experience and raycasting bullets is a great solution for many types of games, but the mechanics I've been working on really put the behavior of the guns front and center, so I really want the bullets to be part of the physics simulation.

I did find some tutorials and code examples that created bullets as rigidbody objects and applied force to them, which is the basic approach I wanted to use. There are some problems with this approach, however. First and foremost is simply that bullets travel very, very fast, and physics calculations only happen so many times a second. On mobile devices, those calculations tend to happen less times per second than on a desktop computer or console because there's simply less computing horsepower available. What can happen as a result, is that bullets can pass right through objects they should have hit. In one frame, the bullet is on the near side of the target, and by the time the next physics frame rolls around, the bullet is on the other side of it, and no collision is detected.

For a desktop game, this is easy to rectify; you just crank up the physics frame rate (which is distinct from the display framerate in Unity) so that the calculations happen more often. For a mobile game, that's not an ideal solution. You have to use the available CPU (and GPU) power efficiently on mobile if you want an overall experience to be good. Fortunately, there's a good solution to this problem on the Unity Wiki. You have your projectile do short ray casts in any physics frame where it travels far enough between frames to have missed a collision.

The bigger problem for me was trying to figure out just what values to use in the physics system. How much mass should the bullet have? How much force do we need to apply to that bullet?

The examples I found seem to have arrived at values by pure trial and error, and they all felt "off" to me. Many of the examples I found used the default mass value for the bullet, for example. In Unity, the default value of "1" is equivalent to 1 kilogram. If you've ever held a bullet, you know that it masses nowhere near a kilogram. Even the giant .50 caliber BMG round doesn't come close. You know what shoot bullets that weighs a kilogram? Battleships, not rifles.

Instead of taking the same trial-and-error approach to getting mass and force values that feel right, I decided I'd do a little research. There's a lot of science behind guns and a lot of people who are interested in guns, so I figured it couldn't be too hard to find real data on real bullets.

It ended up being even easier than I thought it would be. Wikipedia has gathered that data for pretty much every modern form of ammunition, including the exact mass of the bullet, the muzzle velocity, and the amount of energy used to propel the bullet to that velocity.

So, I gathered up that data for an assortment of assault, sniper, and high-powered hunting rifles in a spreadsheet. You can download that spreadsheet here, if you're interested.


Using the bullet's mass in Unity's physics system is easy enough. Just divide the grams by 1000 and that gives the value to use as the projectile's rigid body mass. But, how do we know how much force to apply to the bullet? Unity's documentation for the AddForce() method doesn't say what units it wants for input.

After digging around, I found that somebody had actually gone through the process of figuring out the answer to that while trying to counteract gravity for an object in their game. They determined that the AddForce() method uses 1/50th of a joule as its unit. Since we know how many joules of energy propel each of these modern bullets, we just multiply the number of joules by 50 and feed that value to the AddForce() method.

Great! But modern guns also spin the bullet as it travels down the barrel. In fact, the name "rifle" comes from the grooves in the barrel that cause that spin. After experimenting a bit, I came to the conclusion that for purposes of the game physics, rifling really isn't needed. Rifling helps deal with real world problem that just aren't present in the game's physics engine unless we add them.

But, I decided I still wanted the bullets to spin.

That may seem like an unnecessary bit of realism, but there's actually a reason for it. In some situations, like if you finish a level with a head shot, we're going to slow down time and follow the bullet to its target with the camera. It's a little clichéd, but it's still a cool effect when used sparingly. When we do it, though, I don't want people noticing that the bullet isn't spinning.

And they will.

In the real world, the twist rate of rifling is measured a couple of different ways, including revolutions per minute and the length required to complete one revolution inside the barrel. What it's not measured in is joules. And since this is just for show, I don't want to actually model the rifling into the gun's physics model, because that would be a lot of work and would force the physics engine to do an awful lot of calculations. Instead, I just want to spin the bullet right the moment it is spawned. Unity will let me do that in one line of code using the AddTorque() method. This method takes the same 1/50th of a joule input as AddForce().

But how much torque in joules should I add to the bullet's Z axis?

Honestly, I have no idea, and I really don't think it's worth spending a huge amount of time trying to figure it out since it doesn't actually affect the bullet's trajectory. I know it's a lot less force than is used to propel the bullet itself, so I'm going to start with a small number - 100 units (2 joules) - and see how it looks when we switch to the bullet cam. I'll then tweak the value if it doesn't look right. Sometimes trial and error is the right approach. Or maybe it's the lazy approach. Maybe it's both. Regardless, it's the approach I'm taking here.

I threw together a quick shooting gallery to test my real-world-based gun physics. Yes, it's an ugly shooting gallery. This is what you get when a developer throws something together quickly instead of asking his artists to make it for him.  Despite the ugliness, I'm actually pretty darn happy with the results. Here's what it looks like shooting a gun based on values taken from the .300 Winchester ammunition:



There's still a lot of work to be done on my gun class. I need to get recoil in there, for example, as well as muzzle flash. But, I've got most of the basics down for building a variety of weapons by simply configuring parameters in Unity's inspector. Change the weight and force and a handful of other parameters and you get a gun that behaves and feels very differently. Change the 3D model as well, and you basically have a new, different gun.

On a related note, my early prototypes used the gyroscope for aiming on mobile devices. It had a really natural feel that I loved, but it proved problematic when you zoomed in very far. The tiniest movements from holding the device in your hands would translate into very noticeable, unwanted movement. That movement actually felt like actual shake and scope drift, but beyond about 4x magnification, the game became basically unplayable. I spent some time trying to add stabilization and smoothing to the gyroscope input, but was never happy with the result or the amount of control we had over it.

After a while I admitted defeat and ended up ripping out the gyroscope code and replacing it with code that used the accelerometer for aiming. I then added scope drift back in algorithmically and created a parameter for it. That means we can easily change how steady a gun is when used. A rifle with a bipod, for example, will have almost no drift, while a large gun used while standing will have a fair bit more.

Thursday, October 3, 2013

Turncoat Dev Diary: Concept and Mechanics

As I mentioned in my last post, we now have dedicated game artists working on Turncoat, and we've mostly decided on the mechanics and basic structure of our first game. I'm not quite ready to announce the game's name or share much detail about it until we've finalized that decision and taken some administrative steps such as reserving the app and domain names.

For the first game, we've decided not to make it story-driven. This was a tough call, because our eventual goal is to create large, story-heavy cinematic games. However, we also need to run this as a business. Long cutscenes and story-driven plot would greatly increase the budget and timeline of this first game and probably wouldn't greatly increase our sales.

So, what we're doing is a game that's smaller in scope but set in the universe and takes place in and around the main storyline. Developing a more casual game will allow us to build up a library of game assets to eventually be used in the full story-driven game yet still keep a reasonable timeline for shipping something.

In the last post, I showed you the selection of gun silhouettes that Alex came up with:



We decided to start working with the silhouettes J and K (which are similar) for the first gun the player gets to use. I did a write-up of the characteristics of the gun and wrote a little in-universe history for it to help Alex while visualizing it. My thought was that the player would start with a more general purpose gun; something modular that came in several variants. We settled on an assault rifle that came in regular, sniper and tactical variants. After noodling around for a bit, Alex came turned that into these designs:


When he first sent it to me, I really wanted to find something that needed to be improved. I pretty much failed to find fault with the designs, though. They're pretty much exactly what I was hoping for. The only flaw I found was in the variant names. The "X" designation only applies to the sniper variant. The tactical variant is the RAR-14T, and the regular version is the RAR-14.

RAR stands for "Republic Assault Rifle", and it's pronounced "rawr fourteen".  I was originally going to drop the first R, making "Republic" assumed.  "AR-14" or "Republic AR-14" sounded more like a gun to me than "RAR-14". It turns out, there was a reason for that. The original name of the M16 rifle was "AR-15". Even today, the civilian semi-automatic variant of that gun is sold under the trademarked designation AR-15 by Colt. To keep our distance and not sound too derivative, I decided to stick with the original three-letter acronym pronounced like a word.

Patrick, our other game artist, took Alex's designs and started working on the 3D model for the gun. The model's not finished, but it's looking pretty sharp so far:


Meanwhile, needing a break from designing guns, Alex started working on concept art for the game's first level. We decided that the first level would be a shooting range on board a ship. Our earliest idea was to make a small, long, windowless range. In Deep Fleet ships, space is at a premium, so I initially wanted the space to feel cramped to reflect that, almost as if the designers of the ship had to make room for the rifle range as an afterthought. We explored that idea for a while, but after talking through it, we opted to go in a different direction. We decided that the first level the player sees needed to have a little "wow" to it, and a cramped, dingy range squirreled away in the bowels of the ship just wouldn't give us that. It makes sense in-universe, but it doesn't work for the game.

Essentially, we decided to let aesthetics trump in-Universe realities, and went with a range with large (very bullet proof) windows through which stars, the sun, or maybe even Mars or Earth can be seen. Alex isn't done with the concept art for the shooting range yet but he's off to a good start if you ask me.


The range has a large overhead window looking into space that prevents the room from feeling cramped or small. The shooting stalls can slide in for individual practice, or can be slide out for tactical training. The large pyramid above with the catwalks extending off of it is a holographic projector. Although some elements on the range are real physical items, the targets themselves will be projected holograms. We were originally going to go with targets that pop up the way they do on modern tactical training ranges, but then decided we wanted to go a bit more futuristic.

It'll be interesting to see how much of this changes before we ship the first version of the game, but so far I'm incredibly happy with the progress we're making. On the game mechanics side, I've been experimenting with the gryoscope and trying to make a decision about whether it can be used for certain game mechanics. What I've found is that it's quite well suited to certain situations, but not to others. For example, when you use a scope like the one on the rifle above, and zoom in far, the tiniest movements of your hands cause large movements in the scoped view. While this is somewhat realistic for shooting at long range - holding a gun absolutely perfectly still is impossible - it takes scope drift out of our control.

We need to be able to control things like that. How do we make a gun on a bipod more stable than a gun that's just held, otherwise? How do we make a large, heavy gun behave differently than a smaller one? Contrariwise, how do we keep them from stabilizing their device on a table?

No. Scope drift has to be something we have precise control over. It can't be a byproduct of our control mechanism.

Although I really like the feel of the gyroscope for shooting, I'm becoming convinced that it's not the right mechanism for this game. That being said, I think it might be the right way to control the view in at least some situations when you're not using a scope. The gyroscope is far more accurate than the accelerometer, and any control mechanism that requires screen touches would require screen real estate we're going to need for other controls.

We're making progress and I look forward to sharing more designs with you as we go along. Once we have our ducks in a row and have finalized the game's name and basic story, I'll also share that.

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, 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