- Home /
Simple NPC Character Movement with Mecanim
Okay, so I followed along with the Mecanim tutorial to set up an idle, running, and attack animation for a character to demonstrate the animations in Unity for a class assignment. However, I do not want the character to be controlled by the player as in the Mecanim tutorial. I was able to use this Root Motion documentation to create a simple movement along the x axis with the following code:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Animator))]
public class RootMotionScript : MonoBehaviour {
void OnAnimatorMove()
{
Animator animator = GetComponent<Animator>();
if (animator)
{
Vector3 newPosition = transform.position;
newPosition.x += animator.GetFloat("Runspeed") * Time.deltaTime;
transform.position = newPosition;
}
}
}
This worked but the character clips through the terrain at parts and floats above it at others. I had read that CharacterController can be used to supply the slope navigation I am looking for, but it has no effect with my existing code.
As an alternative, I tried using CharacterController.SimpleMove with the following code:
var speed : float = 3.0;
var rotateSpeed : float = 3.0;
function Update () {
var controller : CharacterController = GetComponent(CharacterController);
// Rotate around y - axis
transform.Rotate(0, Input.GetAxis ("Horizontal") * rotateSpeed, 0);
// Move forward / backward
var forward : Vector3 = transform.TransformDirection(Vector3.forward);
var curSpeed : float = speed * Input.GetAxis ("Vertical");
controller.SimpleMove(forward * curSpeed);
}
@script RequireComponent(CharacterController)
With this method, the character actually falls to the terrain if placed above it, so I know that vertical movement would work, however it no longer applies the root motion to the animator and therefore will not move in the x axis. I would appreciate any guidance in executing either of these method effectively to have a simple run animation across uneven terrain.
Thank you.
When I read about the CharacterController, I didn't realize that you had to apply the Character$$anonymous$$otor script separately. This works with the first set of code.
Answer by GXMark · Nov 13, 2013 at 11:39 PM
You will run into average velocity and blending issues across the network if using root motion animations over a network. Because unity physics are not deterministic from client to server root blending causes many issues and is a non-trivial issue to solve. My advise if you want to build up a stable networking solution for animation is to use in-place animation sequences.