Follow Example(跟随的例子)
动画控制器与上次相同
Follow
using UnityEngine;
using System;
using System.Collections;
[RequireComponent(typeof(Animator))]
//Name of class must be name of file as well
public class Follow : MonoBehaviour {
public Transform TargetObj = null;
protected Animator avatar;
protected CharacterController controller;
private float SpeedDampTime = .25f;
private float DirectionDampTime = .25f;
// Use this for initialization
void Start ()
{
avatar = GetComponent<Animator>();
controller = GetComponent<CharacterController>();
avatar.speed = 1 + UnityEngine.Random.Range(-0.4f, 0.4f);
}
void Update ()
{
if (avatar && TargetObj)
{
if(Vector3.Distance(TargetObj.position,avatar.rootPosition) > 4)
{
avatar.SetFloat("Speed",1,SpeedDampTime, Time.deltaTime);
//当前方向=动画根动画位置 * 坐标Z轴
Vector3 curentDir = avatar.rootRotation * Vector3.forward;
//想去的方向 = 目标到自身距离的归一化(normalized)
Vector3 wantedDir = (TargetObj.position - avatar.rootPosition).normalized;
//用点乘方法判断目标是否在前方
if(Vector3.Dot(curentDir,wantedDir) > 0)
{
//用叉乘来求出目标的方向
//在左侧返回-1
//在右侧返回1
avatar.SetFloat("Direction",Vector3.Cross(curentDir,wantedDir).y,DirectionDampTime, Time.deltaTime);
}
else
{
avatar.SetFloat("Direction", Vector3.Cross(curentDir,wantedDir).y > 0 ? 1 : -1, DirectionDampTime, Time.deltaTime);
}
}
else
{
avatar.SetFloat("Speed",0,SpeedDampTime, Time.deltaTime);
}
}
}
void OnAnimatorMove()
{
controller.Move(avatar.deltaPosition);
//Animator.deltaPosition 获取最后一个评估帧的头像增量位置。
transform.rotation = avatar.rootRotation;
//物体的旋转=avatar.旋转
}
}
向右转
向左转