• unity3d之角色的移动篇 -- 俯视视角下的键盘移动番外篇


    这是一个来自unity官网实例的行走脚本,经过我的简单整理后发布在这里,写的非常好,条理分明,一目了然,运行起来很有操作手感。

    这个脚本是在animator系统下运行的,所以在写这个脚本前需要先对animator controller进行一些简单的设置:

    1. idle状态(默认)和run状态(blend tree,混合了walk和run)

    2.定义一个float类型的参数,idle->run(speed>0.1), run->idle(speed<0.1)

    3.在run的blend tree里将speed作为过渡动画的参数自动匹配阀值(方法:Compute Thresholds,选择speed)

    4.为主角添加刚体和碰撞器

    5.勾选Apply Root Montion,使用模型行走的步伐来计算行走距离

     
    using UnityEngine;
    using System.Collections;
    
    public class test : MonoBehaviour {
        
        public Animator anim;
        public Rigidbody rb;
        
        public float turnSmoothing = 15f;   // 玩家平滑转向的速度
        public float speedDampTime = 0.1f;  // 速度缓冲时间
    
        void FixedUpdate ()
        {
            float h = Input.GetAxis("Horizontal");      
            float v = Input.GetAxis("Vertical");     
            
            MovementManagement(h, v);
        }
        
        
        void MovementManagement (float horizontal, float vertical)
        {
            // 如果横向或纵向按键被按下 也就是说角色处于移动中
            if(horizontal != 0f || vertical != 0f)
            {
                // 设置玩家的旋转 并把速度设为5.5
                Rotating(horizontal, vertical);
                //函数参数解释 anim.SetFloat (当前速度,  最大速度, 加速缓冲时间, 增量时间)
                anim.SetFloat("speed", 5.5f, speedDampTime, Time.deltaTime); 
            }
            else
                // 否则 设置角色速度为0
                anim.SetFloat("speed", 0);
        }
        
        
        void Rotating (float horizontal, float vertical)
        {
            // 创建角色目标方向的向量
            Vector3 targetDirection = new Vector3(horizontal, 0f, vertical);
            
            // 创建目标旋转值 
            //对应参数分别是 1.四元数看向的目标 2.需要沿着旋转的轴
            Quaternion targetRotation = Quaternion.LookRotation(targetDirection, Vector3.up); 
            
            // 创建新旋转值 并根据转向速度平滑转至目标旋转值
            Quaternion newRotation = Quaternion.Lerp(rb.rotation, targetRotation, turnSmoothing * Time.deltaTime);
            
            // 更新刚体旋转值为 新旋转值
            rb.MoveRotation(newRotation);
        }
    }

    PS:

    处理物理效果的代码需要写在FixedUpdate函数内;

    完整行走的三要素分别是动画、旋转、移动, 这个实例把动画和旋转分别写在2个方法里,移动使用模型的步伐自动计算;

     
     
     
  • 相关阅读:
    MySQL之数据表的插入内容 空与非空(六)
    输出杨辉三角形
    输入三个double型的数据,放入到a,b,c三个变量中去,使用条件结构与交换逻辑将这三个变量中的值从小到大排列。
    软件测试
    过程设计工具
    设计原理
    总体设计
    生活,也让别人生活
    计算器案例
    需求分析
  • 原文地址:https://www.cnblogs.com/hellozzz/p/4180613.html
Copyright © 2020-2023  润新知