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。返回值是是否着地。
例子
  1. CharacterController controller= GetComponent<CharacterController>(); 
  2. Vector3 forward= transform.TransformDirection(Vector3.forward); 
  3. float curSpeed = speed * Input.GetAxis ("Vertical"); 
  4. ontroller.SimpleMove(forward * curSpeed); 
CharacterController controller= GetComponent<CharacterController>();
Vector3 forward= transform.TransformDirection(Vector3.forward);
float curSpeed = speed * Input.GetAxis ("Vertical");
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 print ? 在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"); 
function Update () {
	//获得键盘或者摇杆上的方向量(键盘默认是方向键和wasd键控制方向)
	var directionVector = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
	
    //有方向变化
	if (directionVector != Vector3.zero) {
        //取得方向向量的长度
	    var directionLength = directionVector.magnitude;
        //normal 方向向量(向量/长度)
		directionVector = directionVector / directionLength;
		
        //修正长度不大于1
		directionLength = Mathf.Min(1, directionLength);
		
        //为了效果更明显,长度平方扩大
		directionLength = directionLength * directionLength;
		
        //用我们修正后的长度来修正方向向量
		directionVector = directionVector * directionLength;
	}
	
	// 设置移动的方向
	motor.inputMoveDirection = transform.rotation * directionVector;
    //设置跳跃(默认键盘是空格键)
	motor.inputJump = Input.GetButton("Jump");
}

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

[javascript] view plain copy print ? 在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.     } 
function Update() {
    if (!isControllable)
    {
        // 清除所有的输入,如果不处于控制
        Input.ResetInputAxes();
    }
    //按了跳跃键
    if (Input.GetButtonDown ("Jump"))
    {
        //设置按下跳跃键的时间
        lastJumpButtonTime = Time.time;
    }
    //控制角色的方向
    UpdateSmoothedMovementDirection();
    //处理重力
    ApplyGravity ();
    // 处理跳跃逻辑
    ApplyJumping ();
    //计算实际的动作(移动方向和重力方向的)
    var movement = moveDirection * moveSpeed + Vector3 (0, verticalSpeed, 0) + inAirVelocity;
    movement *= Time.deltaTime;
    // 移动角色
    var controller : CharacterController = GetComponent(CharacterController);
    collisionFlags = controller.Move(movement);
    // 动画处理
    if(_animation) {
        if(_characterState == CharacterState.Jumping) //跳跃
        {
            if(!jumpingReachedApex) {//没到达最高点,继续向上
                _animation[jumpPoseAnimation.name].speed = jumpAnimationSpeed;
                _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever;
                _animation.CrossFade(jumpPoseAnimation.name);
            } else {//到了最高点,速度方向改变
                _animation[jumpPoseAnimation.name].speed = -landAnimationSpeed;
                _animation[jumpPoseAnimation.name].wrapMode = WrapMode.ClampForever;
                _animation.CrossFade(jumpPoseAnimation.name);				
            }
        } 
        else 
        {
            if(controller.velocity.sqrMagnitude < 0.1) {//没有方向移动
                _animation.CrossFade(idleAnimation.name);//空闲状态
            }
            else 
            {
                if(_characterState == CharacterState.Running) {//奔跑
                    _animation[runAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, runMaxAnimationSpeed);
                    _animation.CrossFade(runAnimation.name);	
                }
                else if(_characterState == CharacterState.Trotting) {//疾走
                    _animation[walkAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, trotMaxAnimationSpeed);
                    _animation.CrossFade(walkAnimation.name);	
                }
                else if(_characterState == CharacterState.Walking) {//普通走动
                    _animation[walkAnimation.name].speed = Mathf.Clamp(controller.velocity.magnitude, 0.0, walkMaxAnimationSpeed);
                    _animation.CrossFade(walkAnimation.name);	
                }
				
            }
        }
    }
    //在地上
    if (IsGrounded())
    {
        //旋转方向
        transform.rotation = Quaternion.LookRotation(moveDirection);
			
    }	
    else
    {
        //在空中忽略y轴旋转
        var xzMove = movement;
        xzMove.y = 0;
        if (xzMove.sqrMagnitude > 0.001)
        {
            transform.rotation = Quaternion.LookRotation(xzMove);
        }
    }	
    // 跳跃状态,刚好到达地面
    if (IsGrounded())
    {
        //记录到达地面的时间
        lastGroundedTime = Time.time;
        //空中的速度设置为0
        inAirVelocity = Vector3.zero;
        //更改相关状态
        if (jumping)
        {
            jumping = false;
            SendMessage("DidLand", SendMessageOptions.DontRequireReceiver);
        }
    }
}
第三人控制器摄像机脚本ThirdPersonCamera.js

[javascript] view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. function Apply (dummyTarget : Transform, dummyCenter : Vector3) 
  2.     // 没有目标 
  3.     if (!controller) 
  4.         return
  5.     //目标中心和顶点 
  6.     var targetCenter = _target.position + centerOffset; 
  7.     var targetHead = _target.position + headOffset; 
  8.     //计算目标旋转角度和当前角度 
  9.     var originalTargetAngle = _target.eulerAngles.y; 
  10.     var currentAngle = cameraTransform.eulerAngles.y; 
  11.     // 调整目标的真实角度 
  12.     var targetAngle = originalTargetAngle;  
  13.     //按了Fire2(alt)摄像机的方向改变会加快 
  14.     if (Input.GetButton("Fire2")) 
  15.         snap = true
  16.      
  17.     if (snap) 
  18.     { 
  19.         // 靠近角色了,重置snap  
  20.         if (AngleDistance (currentAngle, originalTargetAngle) < 3.0) 
  21.             snap = false
  22.         //计算当前角度 
  23.         currentAngle = Mathf.SmoothDampAngle(currentAngle, targetAngle, angleVelocity, snapSmoothLag, snapMaxSpeed); 
  24.     } 
  25.     // Normal 摄像机动作 
  26.     else 
  27.     { 
  28.         //延迟一点时间 
  29.         if (controller.GetLockCameraTimer () < lockCameraTimeout) 
  30.         { 
  31.             targetAngle = currentAngle; 
  32.         } 
  33.         // 向后走的时候锁住摄像机 
  34.         if (AngleDistance (currentAngle, targetAngle) > 160 && controller.IsMovingBackwards ()) 
  35.             targetAngle += 180;//旋转180 
  36.         //插值改变相机角度 
  37.         currentAngle = Mathf.SmoothDampAngle(currentAngle, targetAngle, angleVelocity, angularSmoothLag, angularMaxSpeed); 
  38.     } 
  39.     //当跳跃时 
  40.     // When jumping don't move camera upwards but only down! 
  41.     if (controller.IsJumping ()) 
  42.     { 
  43.         // 计算目标的高度 
  44.         var newTargetHeight = targetCenter.y + height; 
  45.         if (newTargetHeight < targetHeight || newTargetHeight - targetHeight > 5) 
  46.             targetHeight = targetCenter.y + height; 
  47.     } 
  48.     // 走动时,改变高度 
  49.     else 
  50.     { 
  51.         targetHeight = targetCenter.y + height; 
  52.     } 
  53.     // 计算当前高度 
  54.     var currentHeight = cameraTransform.position.y; 
  55.     currentHeight = Mathf.SmoothDamp (currentHeight, targetHeight, heightVelocity, heightSmoothLag); 
  56.     // 按角度旋转、 
  57.     var currentRotation = Quaternion.Euler (0, currentAngle, 0); 
  58.     //更新相机位置 
  59.     cameraTransform.position = targetCenter; 
  60.     cameraTransform.position += currentRotation * Vector3.back * distance; 
  61.     // 设置相机的高度 
  62.     cameraTransform.position.y = currentHeight; 
  63.     //摄像机一直朝向目标 
  64.     SetUpRotation(targetCenter, targetHead); 
function Apply (dummyTarget : Transform, dummyCenter : Vector3)
{
	// 没有目标
	if (!controller)
		return;
	//目标中心和顶点
	var targetCenter = _target.position + centerOffset;
	var targetHead = _target.position + headOffset;
    //计算目标旋转角度和当前角度
	var originalTargetAngle = _target.eulerAngles.y;
	var currentAngle = cameraTransform.eulerAngles.y;
	// 调整目标的真实角度
	var targetAngle = originalTargetAngle; 
    //按了Fire2(alt)摄像机的方向改变会加快
	if (Input.GetButton("Fire2"))
		snap = true;
	
	if (snap)
	{
		// 靠近角色了,重置snap 
		if (AngleDistance (currentAngle, originalTargetAngle) < 3.0)
			snap = false;
		//计算当前角度
		currentAngle = Mathf.SmoothDampAngle(currentAngle, targetAngle, angleVelocity, snapSmoothLag, snapMaxSpeed);
	}
	// Normal 摄像机动作
	else
	{
        //延迟一点时间
		if (controller.GetLockCameraTimer () < lockCameraTimeout)
		{
			targetAngle = currentAngle;
		}
		// 向后走的时候锁住摄像机
		if (AngleDistance (currentAngle, targetAngle) > 160 && controller.IsMovingBackwards ())
			targetAngle += 180;//旋转180
        //插值改变相机角度
		currentAngle = Mathf.SmoothDampAngle(currentAngle, targetAngle, angleVelocity, angularSmoothLag, angularMaxSpeed);
	}
    //当跳跃时
	// When jumping don't move camera upwards but only down!
	if (controller.IsJumping ())
	{
		// 计算目标的高度
		var newTargetHeight = targetCenter.y + height;
		if (newTargetHeight < targetHeight || newTargetHeight - targetHeight > 5)
			targetHeight = targetCenter.y + height;
	}
	// 走动时,改变高度
	else
	{
		targetHeight = targetCenter.y + height;
	}
	// 计算当前高度
	var currentHeight = cameraTransform.position.y;
	currentHeight = Mathf.SmoothDamp (currentHeight, targetHeight, heightVelocity, heightSmoothLag);
	// 按角度旋转、
	var currentRotation = Quaternion.Euler (0, currentAngle, 0);
    //更新相机位置
	cameraTransform.position = targetCenter;
	cameraTransform.position += currentRotation * Vector3.back * distance;
	// 设置相机的高度
	cameraTransform.position.y = currentHeight;
	//摄像机一直朝向目标
	SetUpRotation(targetCenter, targetHead);
}

  • 总结

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

  • 源码

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

  • 参考文档

http://unity3d.com/learn


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值