///
///
///
using UnityEngine;
using System;
using System.Collections;
[RequireComponent(typeof(Animator))]
//Name of class must be name of file as well
public class RandomCharacters : MonoBehaviour {
public float AvatarRange = 25;
protected Animator avatar;
private float SpeedDampTime = .25f;
private float DirectionDampTime = .25f;
//设定目标位置
private Vector3 TargetPosition = new Vector3(0,0,0);
// Use this for initialization
void Start ()
{
//获得动画组件
avatar = GetComponent<Animator>();
}
void Update ()
{
//判断是否为空
if(avatar)
{
int rand = UnityEngine.Random.Range(0, 50);
//用随机数来切换动画
avatar.SetBool("Jump", rand == 20);
avatar.SetBool("Dive", rand == 30);
//判断两个3为向量的距离
if(Vector3.Distance(TargetPosition,avatar.rootPosition) > 5)
{ //缓慢切换动画,
avatar.SetFloat("Speed",1,SpeedDampTime, Time.deltaTime);
//获得动作系统正前方 根旋转 动画的旋转角度*正前方
Vector3 curentDir = avatar.rootRotation * Vector3.forward;
//朝向目标位置的方向 //目标位置减去动画根位置然后进去归一化//得到朝向目标位置的方向
Vector3 wantedDir = (TargetPosition - avatar.rootPosition).normalized;
//通过点乘来判断动画正前方 和目标位置的方向是否一样
//大于0表示方向接近差不多,等于1表示完全一直,
//小于0表示方向不一样,
if(Vector3.Dot(curentDir,wantedDir) > 0)
{ //通过差乘结果来改变方向值越小 越慢
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);
if(avatar.GetFloat("Speed") < 0.01f)
{
TargetPosition = new Vector3(UnityEngine.Random.Range(-AvatarRange,AvatarRange),0,UnityEngine.Random.Range(-AvatarRange,AvatarRange));
}
}
}
}
}