差乘 点乘的利用

///
///
///

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));
            }
        }
    }       
}             

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值