Super Mario 64 HD! – Custom Character Controller Update

It’s been awhile since I’ve posted on here, and for good reason! To ensure that my Customer Unity Character controller is able to meet a wide variety of use cases, I figured it would be best to create a demo character implementing the tool. I wanted to pick a character that would be reasonably complex, since I figured a simpler one wouldn’t highlight it’s features (or help me discover it’s problems) as well. To that end, I decided to base my implementation on…

Super Mario 64 cover art

The best

Super Mario 64! Aside from being one of the best games of all time and one of my personal favourites, Mario boasts a wide range of moves that would test the limits of my Character Controller. Initially, I planned to grab a Mario model from somewhere, do a couple quick animations and build a controller that would implement a fairly small subset of his moves. However, things quickly got out of hand…

Super Mario 64...now in HD

pls no c&d ninty

…and before I knew it, I had added in virtually all of the moves from the original game, a fully animated Goomba and Bob-Omb, and had begun to build an HD version of Bob-Omb Battlefield, the game’s first level.

Current progress on Bob-Omb Battlefield Redux. Got a ways to go...

Current progress on Bob-Omb Battlefield Redux. Got a ways to go…

In addition to being a huge time sink, this project is serving two purposes: demonstrating the character controller, and helping me learn the ins and outs of 3D art. The Mario model I’m using is borrowed from Mario Galaxy, but it didn’t come with bones, rigging or animations, leaving the task to me. This was made infinity easier by this terrific tutorial I found on character rigging using 3ds Max.

Super Mario, master hula-hooper

Super Mario, master hula-hooper

I plan to release the project on this page sometime in the near future, and hopefully it will help others build their projects!

Editor shot of the same scene as above. SuperCharacterController with three debug spheres enabled on Mario.

Editor shot of the same scene as above. SuperCharacterController with three debug spheres enabled on Mario.

Advertisements

Custom Character Controller in Unity: Part 3 – Analysis of the Physics API

Up until this point I’ve made multiple references to some of the Unity Physics API, but we haven’t really explored it in detail. As an astute reader may have guessed from the title of this entry, that’s what we’ll be doing now. We’ll go through the functions available, analyze some of their associated issues, and ways to overcome them.

As per usual I’ve done my best to avoid doing original research and will be making heavy use of this post from fhhoollm.

Fhhoollolllmm!!

Fhhoollolllmm!!

The Physics API

With many of the functions simply being variations of each other, it shouldn’t take long to go over the details of the Physics Script Reference. I’m not going to bother talking about the methods that have an All variation available, since they are identical other than that the raycast stops immediately at the first contact.

Raycast: Fires a ray in a specified direction for a specified distance (or infinitely far). If an object is contacted, the RaycastHit structure provides useful information about it: where it was contacted, what the normal of the surface was at the contact point, and so on. Because it fires just an infinitely thin ray, this method isn’t particularly use for collision resolution.

CapsuleCastAll: At first glance this seems ideal for usage with a character controller (due to it’s capsule shape), and for the most part it is. It is important to note that as this is a cast it will only detect a collision where the normal of the surface is facing the cast-no backfaces are detected. In addition, the cast does not detect any objects that are within the boundaries of the “capsule” origin of the cast, i.e., it doesn’t detect any objects touching it’s initial position. This is a drawback we will need to overcome if we want it to be a useful tool for our character controller.

CheckCapsule: Right away we have a candidate to solving the problem stated above. CheckCapsule seems to exactly compliment CapsuleCastAll-it will detect all the objects at the initial position of the cast that the CapsuleCast cannot. Unfortunately, it only returns a bool, as opposed to an array of colliders, giving us no information on what objects we actually collided with.

CheckSphere: Same as above, except with a sphere shape.

Linecast: Identical in terms of function to Raycast. Simply a different way of defining the origin, direction, and magnitude of the ray.

OverlapSphere: Now we’re getting somewhere. As far as I can tell, OverlapSphere works exactly as advertised. Bear in mind this note does appear on the docs:

NOTE: Currently this only checks against the bounding volumes of the colliders not against the actual colliders.

…and I really don’t know what this means. I’ve tested it against Box Colliders, Sphere Colliders and Mesh Colliders and it seems to be checking against the actual collider, not just the bounding volume. Note that I am taking bounding volume to mean axis aligned bounding box, and it may mean something different in this case. If not, I’m going to assume it’s a documentation error.

RaycastAll: Same as the Raycast method, except that it does not stop at the first object it contacts.

SphereCastAll: Functions the same as CapsuleCastAll, with the same primary drawback of not detecting objects contained in the sphere defined at the origin of the cast. SphereCast also (like CapsuleCast) does NOT always return the proper normal of the face it collides with. Because it is a sphere that is being cast (rather than an infinitely thin ray in Raycasting) it can collide with the edges of a mesh. When this happens, the hit.normal that is returned is the interpolated value of the normals of the two faces that are joined by the edge. Since CapsuleCasting is just casting with a swept-sphere, it also has the same issue.

In addition to the above tools to detect collisions, Unity also provides a Rigidbody.SweepTestAll method. After testing it, it seems to have identical behavior to the cast methods; faces contained within the collider are not detected by the sweep. I tend to prefer using CapsuleCastAll and SphereCastAll over SweepTest all, as they offer more options (like being able to define your own origin), however SweepTest is useful for box shaped characters, as there is no BoxCast method.

Mesh Colliders

Before we go any further, I want to talk a little bit about mesh colliders. Up until now we’ve focused primarily on the primitive colliders (Box, Sphere, Capsule, etc). However in practice the overwhelming amount of your level’s collision geometry is going to be composed of mesh colliders.

Unlike the primitive colliders, which have their collision representation built from a variety of preset parameters (radius for spheres, height for boxes, and so on), a mesh collider’s collision data is unsurprisingly formed from a 3D mesh. Mesh colliders come in two flavors: Convex and Concave. This article does a terrific job explaining the difference between them.

Since convex hulls must be fully enclosed and Unity limits their size to 255 polygons, they are unideal to be used to represent intricate level geometry. Concave hulls can be of any size, but they come with the drawback of no longer being an enclosed object; instead of being a solid volume, they are essentially just a surface of triangles. This means we can no longer detect if an object is “inside” a concave mesh, since there is no “inside” to check against. This brings us to the problem of phasing. Phasing occurs when a character is moving fast enough (or a wall collider is small enough) that in two frames he travels from one side of the wall to the other, effectively passing through it. Concave mesh colliders amplify this problem by no longer having the ability to detect player collisions occurring “inside” them, making it easy for the player to phase into the mesh.

Controller movement over one frame. His speed is great enough that neither his initial position or final make contact with the thin mesh collider wall in our way

Controller movement over one frame. His speed is great enough that neither his initial or final position make contact with the thin mesh collider wall in his way

Effectively, if we are directly beside a triangle on the surface of a mesh collider with it’s normal facing in the exact inverse direction of our movement vector, the furthest we can move is exactly equal to twice our radius. Considering collision resolution tends to place the character directly flush with the wall, this is a situation that is encountered fairly often. If your character controller is representing a character of about 2 meters (represented as generic units in Unity) high, your radius is typically in the ballpark of 0.5 meters (units). Which means your character can move at most 1 unit per frame. If your game runs at 30 frames per second, you can move at most 30 meters per second, or 108 kilometers per hour. This is pretty damn fast, but if you’re building the latest and greatest Sonic the Hedgehog title it may not be fast enough.

With the controller directly flush with the surface, it cannot move more than twice it's radius or it will phase through the wall

With the controller directly flush with the surface, it cannot move more than twice it’s radius or it will phase through the wall

One solution to this problem is to run your controller’s physics more than once per frame. Alternatively, we can use CapsuleCastAll to check if there are any colliders between our initial and final position every frame. We’ll explore both these options in future articles where we continue to implement the character controller.

Custom Character Controller in Unity: Part 1 – Collision Resolution

After using Unity over the years for various projects, I’ve come to two conclusions: overall it’s a terrific engine that I would recommend to anyone interested in getting into game development, and that it’s built in character controller sucks.  I’ve been working on a custom character controller for a couple weeks and noticed that finding any kind of reference or learning material on the subject is pretty difficult.  So since I couldn’t find anything out there to read…I figured I’d write something instead!  I intend to post a few pieces here outlining what I’ve learned so far and some issues I’ve encountered.  For any actual implementation, I’ll be using the aforementioned Unity game engine.  You can visit their website here and download their latest version here.  I really dig Unity.  It takes care of a lot of the low level under the hood side of game development but still gives you enough freedom to do just about anything.  It also has a really great and active community that is the epitome of helpfulness.

Unfortunately, as previous stated Unity is also home to the world’s worst character controller.  I suppose I should loosely define what a “character controller” is before I build my case against Unity’s.  More or less it’s the code (or class, or whatever) that handles and resolves your character’s collisions in the world.  Unlike boxes and barrels and whatnot that can be taken care of by the rest of the physics engine, characters require special code to behave differently.  However, since we’re doing collision tests, we still need to pick a geometric shape to represent our character.  Most 3D games use a capsule collider.

Capsule collider used to approximate a character's form in Unity

Capsule collider used to approximate a character’s form in Unity

Capsule colliders are great for a wide variety of reasons, but we’ll see that later.  For now, I’m going to go over the basics of character controllers in just 2 dimensions, to keep it simple for now.

CCSetup1

You’ll notice I’ve labelled the axes and x, instead of and y.  This is because I’m going to treat this as a top down view of a three dimensional world, which we’ll eventually move onto.  The character here is seen as a blue circle, as a capsule seen from top view is a circle!  The green rectangle we will treat as a wall.  Ideally, characters cannot walk through walls.  So should the character intersect with it, we’ll want to detect the collision, and properly resolve it.  We’re going to pass over the actual collision detection, i.e., checking to see if the circle is intersecting the box, for two reasons.  One is that Unity has a fair amount of resources (which we’ll go over later) to handle this, and two is that there is a pretty good selection of reference material out there for collision detection.  We’ll focus on getting the colliding object to resolve it’s position properly based on expected behavior.

CCSetup2

Shown above we have the controller attempting to move into the wall.  To prevent this we run a function that performs a sweep test, from the initial position of the controller to the desired position of the movement.  The test detects that a wall is in front of us, and returns the distance.  Using the value we move the controller in the direction of the test the distance the check traveled, placing it directly beside the wall.  (Aside: Unity has several built in functions for this, including Rigidbody.Sweeptest, Physics.SphereCast and Physics.CapsuleCast).

However, this really isn’t the kind of behavior we want.  If we use this method, the character will be immediately halted in any movement he makes if he collides with an object, if even only slightly.  This is undesirable as it doesn’t reflect the way real world objects tend to bounce and slide off each and, more importantly, it would be annoying as hell to play.

CCSetup3

This is a much more desirable behavior.   The initial sweep test is performed in the movement direction for the movement distance.  When the sweeptest contacts the wall, the character is moved directly to it, just like before.  However, this time around we further move the character upwards to make up for the lost movement, which allows it to slide along surfaces.  This is a great example of the desired behavior of the controller, but it isn’t the best way to implement it.  For one, it’s not very efficient: every time you want to move the controller, you need to run this function.  This is fine if you just move it once per frame, but if you plan on doing something different–for whatever reason–you’ll need to rerun the function.  Two, collisions resolution is reliant on character movement direction and distance.  If he just magically finds his way into a solid wall (as character controllers are wont to do) he’s not going to get automatically pushed out.  In practice, I’ve found this method a massive headache.

CCSetup4

Here is that terrifying situation put onto screen.  We see our hero is currently within the walls of the object.  Instead of looking at collision resolution as a response to a movement, like the previous examples, instead we are going to treat it completely independently.  We no longer are concerned with what direction the player moved or how far he moved.  Instead, we will consider only where he is at this moment, and whether his location is a problem or not.  In the above figure, we can see that currently the player is intersecting the wall (he’s inside it!), and therefore his current location is a problem and needs to be rectified.  Since we are no longer resolving collision as a response to movement, we do not know where his previous position was or how far he moved.  All we know is that currently he is stuck inside a wall, and we need to move him out of the wall.  But where to put him?  Just like in previous examples, we should only push him out so that he is just touching the edge of the wall.  We have many locations that are candidates for this…

CCSetup7

Each of the transparent yellow circles indicate a possible position for the character controller that satisfies our goal–to push him out of the wall to a point somewhere on it’s surface.  But which point do we choose?  Simply put, calculate the closest point on the surface of the wall with respect to the controller’s location.

Drawing these diagrams in Photoshop was a huge mistake they take forever

Drawing these diagrams in Photoshop was a huge mistake they take forever

Here we have calculated that the nearest point to our controller’s current location lies to the right of us.  We then move the controller to that point, plus the radius of the controller (shown in red).

This concludes the first part of our epic adventure into the mysterious realm of character controllering.  Next time I’ll start talking about my implementation in Unity, and some of the more complex functions character controllers use.

Acknowledgements and References:

Most of the knowledge here I’ve acquired by exploring two main information sources: a Unity forums post by the user techmage, and reading through/reverse engineering a Unity custom character controller package by user fholm.  I don’t know how to pronounce that either.  Fuhholllme.  Disgusting.  Reminds me of phlegm.  Anyways, you can download his package off his github here, under the RPGController directory.  This is an amazing project overall that I will be exploring the next few sections, and is really terrifically coded.  Apparently he does Unity consulting too if anyone needs that kind of services.  Finally, if anyone has any good reference material for this subject, or anything relating, sharing it here would be a really great way to expand on the topic!