Showing posts with label Animation. Show all posts
Showing posts with label Animation. Show all posts

Tuesday, 2 May 2017

Animation sequence

I have been trying for a while now to create a sequence of animation. By that I mean a chain of animations that play without the user input. Very much like a cutscene or a tutorial, that can be played out to the user without interaction.

After looking up for tutorials I couldn't find anything relevant, so I came up with my own implementation.

I have also played around with the Unity Timeline feature, which is still in experimental mode, and while I was able to create some sequences, I still could not play animations the way I wanted, such as, having the player character move around, shoot, jump and do other things.

In the end I found a solution which, although not optimal, works pretty well and allows me to create scripted animations for each GameObject in the current scene.

I'm still using this  assent, just like the previous posts.

The way I had it in my mind was to have all my sequences as asset files, which I could then plug int a sequence player in the scene.

Firstly, let's take a look at the Sequence script:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public abstract class Sequence :  ScriptableObject {

 public bool playOnce;
 public bool hasBeenPlayed = false;
 public abstract void OnSequenceEnd();
 public abstract IEnumerator sequence(GameObject[] actors);

 protected void CloseAllDialogs(GameObject[] actors)
 {
  for(int i=0; i<actors.Length;i++)
  {
   actors [i].GetComponent<Speak> ().CloseComic ();
  }
 }

}

This is nothing but a base class which will use to create our sequences asset files. As you can see, it's a ScriptableObject, which allows us to create an asset out of it.

The animation sequence itself is going to be a coroutine, which is the IEnumerator on line 6, which will be differet for each animation sequence we wish to write.

The CloseAllDialogs method is strictly related to my current project and should not be relevant for this example.

One limitation I had to work around was the inability of ScriptableObjects to reference objects in the scene. It would have been much easier and neat to have all the GameObjects I wanted to animate in my ScriptableObject file, but that is simply not possible. Instead, the SequencePlayer will be able to "select" objects form the scene and pass them to the scriptable object, and that is the actors GameObject array you see being passed to our co routine on line 6.

This is the SequencePlayer script:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class SequencePlayer : Interactable {

 public GameObject[] actors;
 public Sequence sequence;
 public bool playOnAwake = false;
 public bool playOnCollision = false;
 public float startDelay = 0;

 void Start()
 {
  if (playOnAwake)
   Invoke ("PlaySequence", startDelay);
 
 }

 public void PlaySequence()
 {

   GameController.instance.currentLevel.SetCurrentState (new PlayableLevel_ConversationState ());
  StartCoroutine (sequence.sequence (actors)); 
 
 }

 override public void OnInteract()
 {
  if (playOnCollision) {
  
   Invoke ("PlaySequence", startDelay);
   GetComponent<Collider2D> ().enabled = false;
  
  }
 }

}

This is, in fact, a Monobehavior script. You can see it inherits from a class called Interactable, which is simply a base class I'm using in my project that represents objects that can interact with the player.

This script will be placed on an empty GameObject in the scene, which should have a collider attached to detect the presence of the player character. I decided to do it this way because I want my animations to be triggered by two main factors: either the scene starts or the player has interacted with our SequencePlayer GameObject, which means has reached an area where an animation sequence should be played.

The 2 bool variables on line 5 and 6 determine which one is the trigger method. If the sequence should be played on awake, as soon as the script is initialized the animation is triggered, with a delay if necessary (line 12). Otherwise, will be triggered once the collision has been detected (line 24 - 31).

The GameObject array actors will need to be pre filled with all the objects we wish to animate. This array is then passed to our ScriptableObject sequence, which is going to do all the magic for us.

Let's have a quick look at our scene now:


We only have the player character on the right. At the moment it is off camera, in our animation we will have it walking in the viewport, greet the player and leave.

An empty GameObject is present in the scene, called Sequencer, and has the SequencePlayer script attached. The inspector will look like this:


As you can see, I passed the Player object to the actors array, and I plugged a Sequence file called ExmapleSequence into the Sequence public field (which is a ScriptableObject).

This is the ExampleSequence scriptable object:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
[CreateAssetMenu(fileName="ExampleSequence",menuName="AnimationSequence/ExampleSequence")]
public class ExampleSequence : Sequence {

 override public IEnumerator sequence(GameObject[] actors)
 {
  GameObject playerObj = actors [0];

  playerObj.GetComponent<Rigidbody2D> ().isKinematic = false;

  while (playerObj.transform.position.x < 0) {
   playerObj.GetComponent<CharController> ().Movement (new Vector2 (1, 0));

   yield return null;
  }

  playerObj.GetComponent<CharController> ().Movement (new Vector2 (0, 0));

  yield return new WaitForSeconds (2);

  playerObj.GetComponent<Speak> ().Say ("Greetings!");

  yield return new WaitForSeconds (2);

  playerObj.GetComponent<Speak> ().CloseComic ();

  while (playerObj.transform.position.x >-15) {
   playerObj.GetComponent<CharController> ().Movement (new Vector2 (-1, 0));

   yield return null;
  } 

  OnSequenceEnd ();

 }

 override public void OnSequenceEnd()
 {
  //Currently not used
 }

}

The very first line is used to create the actual asset file. In the editor, if we now navigate to Asset->Create we can see our ExampleSequence asset, which can be instantiated as an asset file in our project folder:


Then, we proceed creating the actual sequence, in the IEnumerator.

In order to move the character around and speak I have created a character controller script, which I am not going to display here as it is quite extensive. However, there are many tutorials on how to create a character controller, but really it's just a script that enables our character movement and apply animations through an AnimatorController.

On line 6 we grab the reference to our player object.

We then proceed to set its RigidBody2D to respond to physics. The while loop will call the Movement(,,,) method of the CharController script which simply moves the object to a certain point, checking the X value of the position. This method also applies animation with the AnimatioController whithin the CharController script.

We then stop the movement (line 16), we wait for a couple of seconds and we get the player to "say" something. This is done very simply with the use of a Canvas in world space. Finally, we close the comic and send the player back the way he came.

And that is it.

This what it looks like in the end:


Clearly, this is not optimized. Each time we need to grab components from the player object, and that is not ideal. To improve on this, we could cache all the components at the beginning of the script and call them accordingly. For this example, this is acceptable.

Conclusion

This simple method is a good starting point to create scripted animations. It can be a little time consuming having to write a complete sequence, but it allows for great control over all the objects we wish to animate. I'm also using this technique to create tutorial sequences for the player, in which the animation sequence is not controller by time, rather, by the user input this time. Before proceeding to the next instruction, instead of using WaitForSeconds(..) we can pass in a while loop, like so:

1
2
3
   do {
    yield return null;
   } while (!Input.GetMouseButtonDown (0));

This way, the script will resume only after the user has tapped the screen.

I think a lot can be done to optimize the scripts, however, depending on your project, this could be a decent solution for cutscenes and scripted animations.

Friday, 19 August 2016

First person melee combat

I believe it's time for some more combat mechanics. In this section, we'll see how we can create a simple but effective melee combat system for a first person controller. The idea is to create something that resembles the combat system you saw in Skyrim or other RPGs of similar fashion.

I am going to use the first person controller found in the standard asset, plus additional assets found here and a nice skybox downloadable here. As for our foe, I found this asset which suits our needs perfectly.

Setting up the scene

Start by creating the scene. I dropped the first person character controller on a plane, placed a skybox to make the level look pretty and finally position the axe as a child of the first person camera in the controller. This is what the game window looks like:



And below is a srceenshot of the hierarchy as it looks after placing these objects in the scene:


You can see that the axe model is placed as a child of the FirstPersonCharacter, which is where the camera is.

Place a capsule collider on it and set it to trigger. You don't need to be super accurate, something like this should do it:


Create now a new layer, which we can call Axe, and set the axe model to this layer.

Since we are here, let's drag the goblin model in the scene too. That particular model looks a bit too big, so I scaled it down to 0.45 for each axis in its transform. Once in the scene, you can remove the script attached to it and place a capsule collider on it and make it fit nicely around the model. Also, the rigidbody should be checked as isKinematic.


This is pretty much all we need in the scene now. The goblin model already comes with some animation, which we are going to script later.

We should now have the player, with the axe, and our goblin, and they both should collide with each other. However, this is our first problem:



When we get close to the goblin model, the axe passes through it. Unless this is something you want to have, Also, if we had to use the collider on our weapon and not set it to trigger, it could be a little problematic for the player to move around, as it might get stuck in other models when rotating and so on.

There are a couple of ways we can fix this: we could write a shader for the axe in order to have it rendered on top of everything, or we can use 2 cameras. We are going with the latter.

Create a new camera and attach it to the FirstPersonCharacter and set the transform to 0,0,0. Let's call it OverlayCamera. The camera should now be in the exact position as the first person camera that comes with the FPScontroller.Now, in the inspector for this camera, set the Clear Flags to Depth Only, the Culling Mask to Axe, and the Depth to 1.



Now, the other camera, which is a component of FirstPersonCharacter. Leave the Clear flags to Skybox, change the Culling mask by removing the Axe layer, and leave the Depth to 0.

At this point, the OverlayCamera is rendering only the axe (or anything on the Axe layer) and it always draws on top of the FirstPersonCharacter camera, because of the Depth parameter of value 1.


No matter how close we get to the goblin, the axe will always be drawn on top.

Axe animation

We should now create an attack animation for the axe. Honestly, I'm really not the best person to show you how to properly create an animation in Unity, I'm still trying to master the art myself. However, I will show you a GIF picture of the final result so you can have an idea of what I am trying to achieve:


This is the attack animation. I also created a couple of idle animation, you will see them in the playable scene. Later on, we will need to add animation events.

The animation controller for the axe is shown below:


There is a sub state machine which I use to trigger some random idle animations, not something we should be concerned about for our purpose. We should in fact focus on the Axe_Attack state, which holds the animation just created. This state can be triggered by Any State via the trigger Attack and will return to the Axe_Idle state once the animation has reached the end. And don't forget to remove Loop from the Axe_Attack animation.

Here are the inspector screenshots of the 2 transition states side by side:


We can now start writing some scripts.

Scripting time


Create a C# script called Axe.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class Axe : MonoBehaviour {

 Animator anim;

 CapsuleCollider cc;


 // Use this for initialization
 void Start () {

  anim = GetComponent<Animator> ();

  cc = GetComponent<CapsuleCollider> ();
  cc.enabled = false;
 
 }


 // Update is called once per frame
 void Update () {

  if (Input.GetMouseButtonDown (0))    
   anim.SetTrigger ("Attack");  
 
 }

 public void ActivateCollider(int active)
 {
  if (active == 0)
   cc.enabled = false;
  else
   cc.enabled = true;
 }
  



 void OnTriggerEnter(Collider c)
 {
  if (c.gameObject.GetComponent<IAxeHittable>()!=null)
{                               cc.enabled = false;
    c.gameObject.SendMessage ("OnGetHitByAxe", 5);

 }
}
}

Pretty simple, after getting all our references we check in the Update function for any mouse click to trigger the attack animation.

The ActivateCollider method is called by animation events: when the axe is about half way extended, we activate the collider in order to trigger the collision. As the axe is animating back to idle position, we deactivate it.


This is necessary, otherwise every time we get close to the goblin it will register a collision, even if we are not attacking.

Also, we deactivate the collider immediately after hitting.

To detect whether the weapon has hit something we use interfaces. If the object collided with implements the interface IAxeHittable, we send a message to it, calling the method OnGetHitByAxe.

This is the interface:

1
2
3
4
public interface IAxeHittable {

 void OnGetHitByAxe(float hitValue);
}

Now, we can create a Goblin script which will implement the interface and attach it to our goblin model.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public class Goblin : MonoBehaviour, IAxeHittable {

 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 
 }

 public void OnGetHitByAxe(float hitValue)
 {
  Debug.Log ("Goblin got hit by Axe!");
 }
}

As you can see, we MUST implement the method OnGetHitByAxe, which we'll use for handling damage to the enemy. At this point, all we do is to print to the console.

Conclusion

This is the basic structure on how to create some simple melee combat mechanics. As always, this can be improved to become a much more efficient and flexible system, which can be as complex or simple as your project would require.

Example scene here

Thursday, 25 February 2016

Avatar Mask

From the Unity website, an avatar mask allow you to isolate parts of a model's anatomy, allowing the rest to ignore an animation.

In this example, I will take our character model (with animations found here) and get it to aim with his rifle.

To achieve that, I will create an avatar mask which will only affect arms and the head of the model, leaving the rest off it to be animated by the underlying animation. Please note that this example will only work with humanoid types models.

First thing, let's take our model into the scene, and remember to change it's animation type to humanoid. (Fig 1).

Fig 1

For basic movement I will use the same animator controller and scripts used in the Third Person Camera post, so I'm not going to re-explain that part. I reused the script called PlayerMovementImp, found on that post. Also, make a copy of that controller. I removed the parameters we do not need and I added a Boolean called Aim.  (Fig 2)

Fig 2
Do not forget to add a Rigidbody and  CapsuleCollider to our character, so we can move I around with the script.

If you saw the Third Person Camera post, the character is animated with its arm resting when idle, and moving accordingly when walking or running. We will override the arms movement using the mask.

Then, drag in the rifle model. to place it correctly, put the rifle object as a child of the player. More specifically, navigate through all the children of the player model until you find an object called Right_WP. Place the rifle as a child of this object at 0,0,0. (Fig 3).

Fig 3

At this point we can create an avatar mask.

Right click in the project folder, select Create -> AvatarMask.

I gave it the very original name PlayerMask.

Select now the avatar mask just created, open the Humanoid tab, and deselect (by clicking on) the legs, foot IK, the little "circle" you see below the character and the  chest. These body parts should turn red, like in Fig 3.

Fig 4

By doing this, any animation played over this mask will only affect the arms and the head of our model. The red coloured parts are disabled and they will be ignored by that animation, and they will be only affected by the animation in the Base Layer.

Let's click now on the animator controller. Go on the Layer tab, click on the little + icon to create a new layer and let's call it Aim Layer. The settings icon on the right will allow us to select the avatar mask we created. Also, give the variable Weight a value of 1and set the Blending to Override. (Fig 4).

Fig 5

The Weight will determine how much of the animation played in this layer we are going to see. If we leave it to 0, we will see nothing at all, the only animation played will be the one in the Base Layer. You will see in the example scene the effects of this parameter.

By choosing Override, the animation on the Aim Layer will completely override the one from the Base Layer, without any blending.

Select now the Aim Layer. We need to drag in 2 animations: one with the player having the arms resting while holding the rifle and the other one with the arms in aiming position.

Navigate to the folder Military_Rifle_01_Free_v2 -> FBX -> Animation, and drag in the animator the 2 clips called MIL2_M3_W2_Stand_Relaxed_Idle and MIL2_M3_W2_Walk_Aim_F_Loop.  Set the idle one as default.

Remember that we do not care about the legs movement, we simply want the arms movement.

Also, these 2 animations are contained in a FBX object, and we have to change, once again, the animation type to humanoid, for both of them.

From the MIL2_M3_W2_Stand_Relaxed_Idle state in the animator, create a transition to the other animation. Uncheck the HasExitTime box and set the conditions that Aim must be true. Do the same thing the other way, only with an opposite condition. You animator should look like the one in Fig 6.

Fig 6


Now, all we have to do is to feed the animator with the Boolean value for Aim.

In the player movement script, add these few line of code somewhere in the FixedUpdate(), where the rest of the movement take place:



1
2
3
bool aim = Input.GetMouseButton (1);

anim.SetBool ("Aim", aim);

Now we can move the player around just like in the other post. Whenever we hold the right mouse button, the player will go in aiming position.

As you will see in the example scene, the rest of the body moves according to the Base Layer animations, moving the character around just as before. When aiming, only the arms and the head will be affected. If you drag the Weight to 0, the arms will be moved by the animation played in the Base Layer, and they will animate according to the state the character is in.

Example scene here.

Sunday, 31 January 2016

Animation Events and Animator Override Controller

Animation evens are really useful when we want something to happen that needs to be triggered at a particular point during the playing of an animation.

In this scene, for example, our character will perform a "shooting fireball like" animation. To make it look good, we need the fireball to be spawn at a specific moment of the animation.
For this little project I used the same character model we used last time found here , the KY Magic Effect Free found here and the Magic Pack animations found here.

I also reused the animator controller we created in the previous post. I will now show you how we can reuse the same controller but with different animations or with new animations added.

Let's drag in the model and do not forget to change the rig to humanoid. Let's rename it Player.

Now we create the animation controller. Since or character will move in the exact same way as the character of our last post, we are going to reuse the same controller. But we want to add one animation to it, so we are going to use an Animator Override Controller. To create one, right click in the Project folder then choose Create -> Animation Override Controller and let's call it PlayerOverrideController. Do not forget to check the Apply Root Motion box.

If we select our controller, we can see that there is one parameter empty that expects a Controller. Here we can place the animator we created in the previous post, which I believe is called Player. We can now see the all the animations we set up last time, the parameters and the blend tree Motion are available for our new controller.(Fig 1).

Fig 1

This allows for a quick reuse of the same state machine, without having to recreate a whole new one to achieve the same thing. This also lets us modify a state machine without touching the original controller.

We can now drag in our controller a new animation. Let's get it from the folder Mixamo then MagicPack -> Animations and it's called Standing_1H_Magic_Attack_03. We can simply drag it and drop it in our animator controller window and that will create a new state. Rename it "Shoot". As we are still in the animator window, let's create a new parameter of type Trigger and call it Shoot.

Too create a transition, right click on the Motion state and select MakeTransition. To pint the arrow to the shooting state, simply click on it. Let's do the same thing but in revers, from the shooting state to our Motion state. (Fig 2).

Fig 2
We want to translate to the shooting animation whenever the parameter Shoot is triggered, and we want to go back to motion when the shooting animation is finished. To set this up, first click on the transition arrow from Motion to Shoot. Uncheck the HasExitTime parameter and, in the Conditions tab below, click the + sign to add our new trigger parameter Shoot. (Fig 3).

Fig 3
Now let's click on the other arrow. Here, we'll leave the HasExitTime box checked and we can leave the default settings as they are for now. However, I tweaked the blending points I little in order to get a better transition (for my opinion). I did that by dragging around the 2 little blue arrows you see in the graph below. (Fig 4).

Fig 4

Before we set up the animation event, we need to create the script that will handle the shooting and a script for the actual "Magic ball" to move an die out. Create a new C# script called Shooting and one called MagicBall.

Let's also set up the MagicBall object: in the KY_Effects folder, go to MagicEffectsPartFree -> prefab and choose ErekiBall2. You can of course pick any one you like. Let's add a RigidBody component, uncheck the UseGravity box. Then add  SphereCollider, adjust it if you will and check isTrigger. We don't really need colliders and rigidbody for this example, but I is good practice to give these components to moving objects. Finally, let's add the MagicBall script and that's it. We no longer need this object in the scene, so we can drag It into the project folder so a prefab will be created, and then we can delete it from the scene.

Here is the MagicBall C# script:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class MagicBall : MonoBehaviour {

 Vector3 direction;
 float speed = 10;

 Rigidbody rb;


 // Use this for initialization
 void Start () {

  rb = GetComponent<Rigidbody> ();
  StartCoroutine (die ());
 
 }

 IEnumerator die()
 {
  yield return new WaitForSeconds (5);
  Destroy (this.gameObject);
 }
 
 // Update is called once per frame
 void Update () {
 
 }

 void FixedUpdate()
 {
  rb.MovePosition (rb.transform.position + direction * speed * Time.deltaTime);


 }

 public void setDirection(Vector3 dir)
 {
  direction = dir;
  
 }
}

The direction variable is going to be set later by the Shooting script via the method setDirection(...) (Line 35).  In the fixed update function we simply move the rigidbody of the object accordingly. We also start the corotine die() as soon as the object is created (Line 13), so our Magic Ball will destroy itself after 5 seconds. Now, the magic ball is complete.

Let's create a new empty game object called ShootingPoint. This is going to be an empty game object that will handle the spawning of our ball. Place it as a child of our Player object, and set its transform to X: 0.744,Y: 0.62,Z: 0.511. (Fig 5). This will ensure that the ball will spawn right where the hand of the character model is.

Fig 5
Now let's add to the ShootinPoint object the C# script Shooting. Below is the script itself:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Shooting : MonoBehaviour {

 public GameObject prefab;

 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 
 }

 public void ShootBall(Vector3 v)
 {
  GameObject ball = Instantiate (prefab, transform.position, Quaternion.identity) as GameObject;

  ball.GetComponent<MagicBall> ().setDirection (v);
  
 }
}

The public game object variable is going to be our MagicBall prefab we created earlier, so DO NOT forget to add the prefab to the public variable in the inspector. (Fig 6)

Fig 6

Then, when the ShootBall method is called, we instantiate a Magic Ball in the scene (line 17), grab the MagicBall script and call the method setDirection and pass it the direction vector (line 19).

Finally, let's create a last C# script called PlayerMovement, which is going to be identical to our last script from the previous post and will only have one additional method called Shoot.




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class PlayerMovement : MonoBehaviour {

 public float dampSpeed;
 public float dampRotation;


 Animator anim;
 Vector3 originalPos;
 Shooting shooting;

 // Use this for initialization
 void Start () {

  anim = GetComponent<Animator> ();
  shooting = GetComponentInChildren<Shooting> ();
  originalPos = transform.position;

 }

 // Update is called once per frame
 void Update () {

  float speed = Input.GetAxis ("Vertical")/2;
  float rot = Input.GetAxis ("Horizontal");

  if (Input.GetKey (KeyCode.Space))
   speed *= 2;

  if (Input.GetKey (KeyCode.R))
   transform.position = originalPos;

  if (Input.GetMouseButtonDown (0))
   anim.SetTrigger ("Shoot");

 

  anim.SetFloat ("Speed", speed,dampSpeed,Time.deltaTime);
  anim.SetFloat ("Rotation", rot,dampRotation,Time.deltaTime);



 }

 public void Shoot()
 {
  shooting.ShootBall (this.transform.forward);
 }
}

We get a reference of the Shooting coming from the child object ShootingPoint (line 9 and 15) an the method Shoot() simply call the ShootBall method of the Shooting script, passing it the transform.forward of the player model object so the magic ball will move towards the direction our character is facing. Also, we detect if there's a mouse click and, if so, the variable Shoot in the animator will be set, triggering the shooting animation (line 32,33).

At this point, we can go on and create the animation event that will call the aforementioned Shoot() method. Select the Player object and go to Window -> Animation. Once on this window, open the animation list on the top left and select Standing_1H_Magic_Attack_Free. by keeping an eye on our character in the editor window, drag the red line forward at around 0.22, as that is the exact moment of the animation at which we want the magic ball to spawn. (Fig 7).

Fig 7
To add an animation event, click on the "stick like" icon on the top left. hat icon will appear exactly where your red line is placed on the time line. By double clicking on that, we can select the function to be called. (Fig 8).

Fig 8
All done! Now everything is set up and our character should move around and shoot magic balls at every click.

One thing to remember: when adding animation events, we can only call void types functions which accept primitive parameters and are part of a script attached to the same game object which is playing the current animation.

Example scene of the final result here.

Friday, 29 January 2016

Blend Trees for smooth animations

Blend trees are a great tool that we can use in Unity if we want our characters to have smooth animations.

For this project I will use some of the standard asset, and this model.

Let's start by going in the Mobility_01_Free_v2 folder, FBX and locate the character model (MotusMan_v2). Before we drag it into the scene we need to change its rig. This is simply done by selecting the Rig tab, and change the Animation Type to Humanoid. Then click Apply. (Fig 1)


Fig 1

Now we create an Animator Controller and we assign it to our player. Let's also set the variable Apply Root Motion.

Open the Animator Controller window and create a new blend tree by right clicking and then select Create State -> from New Blendtree (Fig 2).

Fig 2

Now create 2 parameters of type float called Speed and Rotation, change the Blend Type to 2D Freeform Cartesian and assign the newly created float parameters in the fields below. (Fig 3).

Fig 3

Now we can start all the motion fields in the motion tab below. I will use the animations found in the standard asset package, in the folder StandardAssets -> Characters -> ThirdPersonCharacter -> Animation. Remember to drag in only the motion, not the whole prefab.We will need a total of 15 motion fields. You will see in Fig 4 which animations I picked and how I set them up.

Fig 4

Now, I could let the engine compute the values needed for the blending, based on the root motion, but I used another trick instead. Since we are going to feed in the blend tree variables (Rotation and Speed) with the Input.GetAxis("") method, we are only going to et values from 0 to 1.So, this is what I did: for each motion field, the Pos X parameter reresents our rotation. Therefore, I set it to 1 for every animation that involves a sharp rotation to the right, 0.5 for a "less sharp" rotation to the right. Same thing for the left rotation, but with negative values. Then, for the animation that requires no rotation, I set it to 0.

The other parameter, Pos Y, is our speed: I set it to 0 for every animation that has no forward movement, 0.5 for walking animations and 1 for running animations.

Depending on the values we are going  to feed in our blend trees, the engine will blend these animations together accordingly.

Now we can create the script that will pass values to the animator controller. It is actually very simple.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class PlayerAnimation : MonoBehaviour {

 public float dampSpeed;
 public float dampRotation;

 public Slider speedSlider;
 public Slider rotatioSlider;

 Animator anim;

 // Use this for initialization
 void Start () {

  anim = GetComponent<Animator> ();
 
 }
 
 // Update is called once per frame
 void Update () {

  float speed = Input.GetAxis ("Vertical")/2;
  float rot = Input.GetAxis ("Horizontal");

  if (Input.GetKey (KeyCode.Space))
   speed *= 2;

  dampSpeed = speedSlider.value;
  dampRotation = rotatioSlider.value;

  anim.SetFloat ("Speed", speed,dampSpeed,Time.deltaTime);
  anim.SetFloat ("Rotation", rot,dampRotation,Time.deltaTime);
 
 }
}

In this script we simply get the animator component (Line 14), and we pass it in the values of speed and rotation from the keyboard (Line 30,31). Notice how on line 21 I divide by half the value obtained, so we can only get a maximum of 0.5 (Input.GetAxis() returns a value from 0 to 1).
By doing so, we will assign a 0.5 to the Speed variable of the animator, triggering the walking animation. Then, if we press space (Line 24,25), I double the value of speed, bringing it to 1 and, therefore, triggering the run animation. A pretty cheap trick, but gets the job done.

Additionally, we apply damping to our animations. Damping is a way to smooth out the values passed to the animator. You can experiment with it in the example scene, as you can see the values for damping come from 2 sliders that you can modify while playing the scene so you will have a good idea of what damping is for.

At this point our character is ready and will move around our empty scene freely and in a very "smooth" way.

Example scene here.