我们要控制角色的移动,能够所有细节都由自己来实现。控制角色模型的移动,同一时候移动摄影机,改变视角。当然Unity也提供了一些组件,能够让我们做更少的工作,实现我们所期望的功能。今天我们就一起系统来学习相关的内容吧。

  • Charactor Controller(角色控制器)

"角色控制器同意你在受制于碰撞的情况下非常easy的进行运动,而不用处理刚体。角色控制器不受力的影响,只当你调用Move函数时才运动。然后它将运行运动,可是受制于碰撞。"(---from unity3d官方文档)  我们通常在人物模型上加上这个组件后,就能够控制模型的移动了。要注意的一点是。加了角色控制器后,他就不受重力影响。所以要自己在move函数中处理重力的情况。即我们要自己出来y轴方向上的速度变化。


  • 两个重要的函数

1.function SimpleMove (speed : Vector3) : bool


以一定的速度移动。将忽略Y轴上的速度。单位是m/s。重力被自己主动应用。建议每帧仅仅调用一次Move或者SimpleMove。返回值是是否着地。


样例


  1. CharacterController controller= GetComponent<CharacterController>();  
  2. Vector3 forward= transform.TransformDirection(Vector3.forward);  
  3. float curSpeed = speed * Input.GetAxis ("Vertical");  
  4. ontroller.SimpleMove(forward * curSpeed);  


2.function Move (motion : Vector3) : CollisionFlags


通过动力来移动控制器。动力仅仅受限制于碰撞。它将沿着碰撞器滑动。这个函数不应用不论什么重力



假设仅仅是单纯控制玩家的移动,那么用Character Controller足够了。假设还涉及到视角的切换。Unity提供了相关的组件。在项目中引入Character Controller(Asset->Import Asset),就能够将角色控制器组件导入我们的项目了。


  • 第一人称控制器

经典的游戏CS就是第一人称视角的,摄像机就是我们的视角。人物的移动,导致视角的移动。(源代码first.unity)


1.删除默认的摄像机


2.新建一个地形Terrain


3.从角色控制器组件中引入 First Person Controller到项目中


4.拖动First Person Controller到合适的位置


我们就能够看到效果了,以第一人称的视角移动,巡视整个场景。鼠标控制总体视角,方向键或者wasdbutton控制摄像机的移动。


  • 第三人称控制器

非常多角色扮演游戏(wow,dota)经常使用到第三人称视角。摄像机离我们的角色保持有一定距离,能够具体看到我们所扮演角色的各种行为动作。(源代码third.unity)


1.创建一个地形


2.引入3rd Person Controller组件到项目中


3.改动默认摄像机的Tag为MainCamera


4.选中3rd Person Controller组件,将其 Third Person Camera 设置为MainCamera


能够看到效果了,能够看到扮演的角色。方向键或者wasd按键能够控制角色的移动,同一时候能够发现整个视角也会跟着移动



效果图


unity playersetting version 代码控制 unity 控制台_Time



  • 核心代码解读

第一人称控制器脚本FPSInputController.js

1. function Update () {  
2. //获得键盘或者摇杆上的方向量(键盘默认是方向键和wasd键控制方向)  
3. var directionVector = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));  
4.       
5. //有方向变化  
6. if (directionVector != Vector3.zero) {  
7. //取得方向向量的长度  
8. var directionLength = directionVector.magnitude;  
9. //normal 方向向量(向量/长度)  
10.         directionVector = directionVector / directionLength;  
11.           
12. //修正长度不大于1  
13.         directionLength = Mathf.Min(1, directionLength);  
14.           
15. //为了效果更明显,长度平方扩大  
16.         directionLength = directionLength * directionLength;  
17.           
18. //用我们修正后的长度来修正方向向量  
19.         directionVector = directionVector * directionLength;  
20.     }  
21.       
22. // 设置移动的方向  
23.     motor.inputMoveDirection = transform.rotation * directionVector;  
24. //设置跳跃(默认键盘是空格键)  
25. "Jump");  
26. }  
 
 第三人称角色控制器ThirdPersonController.js
 
1. function Update() {  
2. if (!isControllable)  
3.     {  
4. // 清除全部的输入,假设不处于控制  
5.         Input.ResetInputAxes();  
6.     }  
7. //按了跳跃键  
8. if (Input.GetButtonDown ("Jump"))  
9.     {  
10. //设置按下跳跃键的时间  
11.         lastJumpButtonTime = Time.time;  
12.     }  
13. //控制角色的方向  
14.     UpdateSmoothedMovementDirection();  
15. //处理重力  
16.     ApplyGravity ();  
17. // 处理跳跃逻辑  
18.     ApplyJumping ();  
19. //计算实际的动作(移动方向和重力方向的)  
20. var movement = moveDirection * moveSpeed + Vector3 (0, verticalSpeed, 0) + inAirVelocity;  
21.     movement *= Time.deltaTime;  
22. // 移动角色  
23. var controller : CharacterController = GetComponent(CharacterController);  
24.     collisionFlags = controller.Move(movement);  
25. // 动画处理  
26. if(_animation) {  
27. if(_characterState == CharacterState.Jumping) //跳跃  
28.         {  
29. if(!jumpingReachedApex) {//没到达最高点,继续向上  
30.                 _animation[jumpPoseAnimation.name].speed = jumpAnimationSpeed;  
31.                 _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever;  
32.                 _animation.CrossFade(jumpPoseAnimation.name);  
33. else {//到了最高点,速度方向改变  
34.                 _animation[jumpPoseAnimation.name].speed = -landAnimationSpeed;  
35.                 _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever;  
36.                 _animation.CrossFade(jumpPoseAnimation.name);                 
37.             }  
38.         }   
39. else   
40.         {  
41. if(controller.velocity.sqrMagnitude < 0.1) {//没有方向移动  
42. //空暇状态  
43.             }  
44. else   
45.             {  
46. if(_characterState == CharacterState.Running) {//奔跑  
47.                     _animation[runAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, runMaxAnimationSpeed);  
48.                     _animation.CrossFade(runAnimation.name);      
49.                 }  
50. else if(_characterState == CharacterState.Trotting) {//疾走  
51.                     _animation[walkAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, trotMaxAnimationSpeed);  
52.                     _animation.CrossFade(walkAnimation.name);     
53.                 }  
54. else if(_characterState == CharacterState.Walking) {//普通走动  
55.                     _animation[walkAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, walkMaxAnimationSpeed);  
56.                     _animation.CrossFade(walkAnimation.name);     
57.                 }  
58.                   
59.             }  
60.         }  
61.     }  
62. //在地上  
63. if (IsGrounded())  
64.     {  
65. //旋转方向  
66.         transform.rotation = Quaternion.LookRotation(moveDirection);  
67.               
68.     }     
69. else  
70.     {  
71. //在空中忽略y轴旋转  
72. var xzMove = movement;  
73.         xzMove.y = 0;  
74. if (xzMove.sqrMagnitude > 0.001)  
75.         {  
76.             transform.rotation = Quaternion.LookRotation(xzMove);  
77.         }  
78.     }     
79. // 跳跃状态,刚好到达地面  
80. if (IsGrounded())  
81.     {  
82. //记录到达地面的时间  
83.         lastGroundedTime = Time.time;  
84. //空中的速度设置为0  
85.         inAirVelocity = Vector3.zero;  
86. //更改相关状态  
87. if (jumping)  
88.         {  
89. false;  
90. "DidLand", SendMessageOptions.DontRequireReceiver);  
91.         }  
92.     }  
93. }  
 
 第三人控制器摄像机脚本ThirdPersonCamera.js
 
 
1. function Apply (dummyTarget : Transform, dummyCenter : Vector3)  
2. {  
3. // 没有目标  
4. if (!controller)  
5. return;  
6. //目标中心和顶点  
7. var targetCenter = _target.position + centerOffset;  
8. var targetHead = _target.position + headOffset;  
9. //计算目标旋转角度和当前角度  
10. var originalTargetAngle = _target.eulerAngles.y;  
11. var currentAngle = cameraTransform.eulerAngles.y;  
12. // 调整目标的真实角度  
13. var targetAngle = originalTargetAngle;   
14. //按了Fire2(alt)摄像机的方向改变会加快  
15. if (Input.GetButton("Fire2"))  
16. true;  
17.       
18. if (snap)  
19.     {  
20. // 靠近角色了,重置snap   
21. if (AngleDistance (currentAngle, originalTargetAngle) < 3.0)  
22. false;  
23. //计算当前角度  
24.         currentAngle = Mathf.SmoothDampAngle(currentAngle, targetAngle, angleVelocity, snapSmoothLag, snapMaxSpeed);  
25.     }  
26. // Normal 摄像机动作  
27. else  
28.     {  
29. //延迟一点时间  
30. if (controller.GetLockCameraTimer () < lockCameraTimeout)  
31.         {  
32.             targetAngle = currentAngle;  
33.         }  
34. // 向后走的时候锁住摄像机  
35. if (AngleDistance (currentAngle, targetAngle) > 160 && controller.IsMovingBackwards ())  
36. //旋转180  
37. //插值改变相机角度  
38.         currentAngle = Mathf.SmoothDampAngle(currentAngle, targetAngle, angleVelocity, angularSmoothLag, angularMaxSpeed);  
39.     }  
40. //当跳跃时  
41. // When jumping don't move camera upwards but only down!  
42. if (controller.IsJumping ())  
43.     {  
44. // 计算目标的高度  
45. var newTargetHeight = targetCenter.y + height;  
46. if (newTargetHeight < targetHeight || newTargetHeight - targetHeight > 5)  
47.             targetHeight = targetCenter.y + height;  
48.     }  
49. // 走动时,改变高度  
50. else  
51.     {  
52.         targetHeight = targetCenter.y + height;  
53.     }  
54. // 计算当前高度  
55. var currentHeight = cameraTransform.position.y;  
56.     currentHeight = Mathf.SmoothDamp (currentHeight, targetHeight, heightVelocity, heightSmoothLag);  
57. // 按角度旋转、  
58. var currentRotation = Quaternion.Euler (0, currentAngle, 0);  
59. //更新相机位置  
60.     cameraTransform.position = targetCenter;  
61.     cameraTransform.position += currentRotation * Vector3.back * distance;  
62. // 设置相机的高度  
63.     cameraTransform.position.y = currentHeight;  
64. //摄像机一直朝向目标  
65.     SetUpRotation(targetCenter, targetHead);  
66. }