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.旋转
	}
}

在这里插入图片描述
向右转
在这里插入图片描述
向左转
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值