Unity手游之路<七>角色控制器

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

(转载请注明原文出处http://blog.csdn.net/janeky/article/details/17406095

  • Charactor Controller(角色控制器)
"角色控制器允许你在受制于碰撞的情况下很容易的进行运动,而不用处理刚体。角色控制器不受力的影响,仅仅当你调用Move函数时才运动。然后它将执行运动,但是受制于碰撞。"(---from unity3d官方文档)  我们通常在人物模型上加上这个组件后,就可以控制模型的移动了。要注意的一点是。加了角色控制器后,他就不受重力影响。所以要自己在move函数中处理重力的情况。即我们要自己出来y轴方向上的速度变化。
  • 两个重要的函数
1.function SimpleMove (speed : Vector3) : bool
以一定的速度移动。将忽略Y轴上的速度。单位是m/s。重力被自动应用。建议每帧只调用一次Move或者SimpleMove。返回值是是否着地。
例子
[csharp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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到合适的位置
我们就可以看到效果了,以第一人称的视角移动,巡视整个场景。鼠标控制整体视角,方向键或者wasd按钮控制摄像机的移动。
  • 第三人称控制器
很多角色扮演游戏(wow,dota)常用到第三人称视角。摄像机离我们的角色保持有一定距离,可以详细看到我们所扮演角色的各种行为动作。(源码third.unity)
1.创建一个地形
2.引入3rd Person Controller组件到项目中
3.修改默认摄像机的Tag为MainCamera
4.选中3rd Person Controller组件,将其 Third Person Camera 设置为MainCamera
可以看到效果了,可以看到扮演的角色。方向键或者wasd按键可以控制角色的移动,同时可以发现整个视角也会跟着移动

效果图


  • 核心代码解读
第一人称控制器脚本FPSInputController.js
[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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.     motor.inputJump = Input.GetButton("Jump");  
  26. }  

第三人称角色控制器ThirdPersonController.js

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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.                 _animation.CrossFade(idleAnimation.name);//空闲状态  
  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.             jumping = false;  
  90.             SendMessage("DidLand", SendMessageOptions.DontRequireReceiver);  
  91.         }  
  92.     }  
  93. }  
第三人控制器摄像机脚本ThirdPersonCamera.js

[javascript]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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.         snap = true;  
  17.       
  18.     if (snap)  
  19.     {  
  20.         // 靠近角色了,重置snap   
  21.         if (AngleDistance (currentAngle, originalTargetAngle) < 3.0)  
  22.             snap = 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.             targetAngle += 180;//旋转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. }  

  • 总结

角色控制,可以方便的控制游戏的视角。在很多游戏中,可以直接使用该组件,减少我们的重复开发工作

  • 源码

http://pan.baidu.com/s/1BwArJ

  • 参考文档

http://unity3d.com/learn
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能。此外,在求职或创业过程中,具备跨平台开发的大学生将更具竞争。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值