码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2014-12-23 19:00:44      阅读:321      评论:0      收藏:0      [点我收藏+]

标签:

这是一个来自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个方法里,移动使用模型的步伐自动计算;

 

 
 
 

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

标签:

原文地址:http://www.cnblogs.com/hellozzz/p/4180613.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!