皇家每羊历险记(四)——角色移动

现在来添加角色移动 ,创建PlayMovement脚本挂载到角色上,使用lerp函数改变玩家方向,使用Input获得玩家的输入,建立两个函数分别为MovementManagement和Rotating控制角色移动和转向,代码比较简单,如下所示

 1 public class Player : MonoBehaviour {

 2 

 3     public CharacterController characterController;

 4 

 5     private float moveH = 0.0f;

 6     private Vector3 moveDirection = Vector3.zero;

 7     private Vector3 rotateDirection = Vector3.zero;

 8 

 9     public float turnSmoothing = 15f;   // 玩家平滑转向的速度

10     public float speedDampTime = 0.1f;  // 速度缓冲时间

11 

12 

13     private Animator anim;              // Animator组件引用

14     private HashIDs hash;

15 

16     // Use this for initialization

17     void Start()

18     {

19         characterController = GetComponent<CharacterController>();

20     }

21 

22     void Awake()

23     {

24         anim = GetComponent<Animator>();

25         hash = GameObject.FindGameObjectWithTag("GameController").GetComponent<HashIDs>();

26     }

27     

28     // Update is called once per frame

29     void Update () {

30     

31     }

32 

33     void FixedUpdate()

34     {

35         float h = Input.GetAxis("Horizontal");

36         float v = Input.GetAxis("Vertical");

37 

38         MovementManagement(h, v); 

39     }

40 

41     void MovementManagement(float horizontal, float vertical)

42     {

43         // 如果横向或纵向按键被按下 也就是说角色处于移动中

44         if (horizontal != 0f || vertical != 0f)

45         {

46             // 设置玩家的旋转 并把速度设为5.5

47             Rotating(horizontal, vertical);

48             anim.SetFloat(hash.speedFloat, 5.5f, speedDampTime, Time.deltaTime);  //函数参数解释 anim.SetFloat (当前速度,  最大速度, 加速缓冲时间, 增量时间)

49         }

50         else

51             // 否则 设置角色速度为0

52             anim.SetFloat(hash.speedFloat, 0);

53     }

54 

55     void Rotating(float horizontal, float vertical)

56     {

57         // 创建角色目标方向的向量

58         Vector3 targetDirection = new Vector3(horizontal, 0f, vertical);

59 

60         // 创建目标旋转值 并假设Y轴正方向为"上"方向

61         Quaternion targetRotation = Quaternion.LookRotation(targetDirection, Vector3.up); //函数参数解释: LookRotation(目标方向为"前方向", 定义声明"上方向")

62 

63         // 创建新旋转值 并根据转向速度平滑转至目标旋转值

64         //函数参数解释: Lerp(角色刚体当前旋转值, 目标旋转值, 根据旋转速度平滑转向)

65         Quaternion newRotation = Quaternion.Lerp(GetComponent<Rigidbody>().rotation, targetRotation, turnSmoothing * Time.deltaTime);

66 

67         // 更新刚体旋转值为 新旋转值

68         GetComponent<Rigidbody>().MoveRotation(newRotation);

69     }

70 }

如此角色便可以移动和转向了。

你可能感兴趣的:(角色)