首页 > 技术文章 > 角色控制器控制前后左右移动

yuanxiaoyu 2021-11-05 20:55 原文

角色控制器控制前后左右移动

大致思路:

定义一个public CharacterController PlayCC;即声明一个CharcterController的对象,
在Start方法里获取该对象, PlayCC = this.GetComponent<CharacterController>();
写一个private void PlayMove()函数,用于改变固定时间帧的motionvalue值/设置物体跳跃以及判断是否接触地面/以及动画控制器的播放;
将motionvalue传进PlayCC.Move()里,通过CharacterController控制玩家移动。

 

截取了部分代码,描述角色前后左右移动的实现:

  private void PlayMove()//同样需拖进FixedUpdate函数里
  {
      if (PlayCC == null) return;
      Vector3 motionvalue = Vector3.zero;//初始化motionvalue为zero
      float h = Input.GetAxis("Horizontal");
      float v = Input.GetAxis("Vertical");//获取键盘的输入(WASD),在Edit下的 ProjectSetting下的InputManager里可以设置。   
  //1. Vertical             对应键盘上面的上下箭头,当按下上或下箭头时触发
  //2. Horizontal           对应键盘上面的左右箭头,当按下左或右箭头时触发
  
     motionvalue -= this.transform.forward * movespeed * v * Time.fixedDeltaTime;
     motionvalue -= this.transform.right * movespeed * h * Time.fixedDeltaTime;
 //这里我们开始定义了 public float movespeed = 10;
 //通过这两句获取了每帧调用的motionvalue前后左右移动的值
 
     vspeed += -gravity * Time.fixedDeltaTime;//这里我们在开始定义了 public float gravity = 2f;
     public float vspeed = 0; //初始化vspeed。
 
     motionvalue += Vector3.up * vspeed * movespeed * Time.fixedDeltaTime;//再让这个速度加到motionvalue上
 
      if (CheckPoint != null)//开始定义一个public Transform CheckPoint;设置CheckPoint的Y坐标为0.35,由于角色碰撞器的大小为1,半径为0.7,从而当角色碰撞器到达地面时,触发以下if条件。
   {
         if (Physics.CheckSphere(CheckPoint.position, radius, ground) && vspeed < 0)
      {
 
           isground = true;//设置布尔类型的变量取名为isground,初始化为false,
           vspeed = 0;//更改Player的速度为0
 
      }
 
 
   }
 //设置Player的跳跃
      if (isground)
   {
         if (Input.GetButtonDown("Jump"))//当按下Jump(unity默认空格键键入)
      {
 
           vspeed = Mathf.Sqrt(maxheight * 2 / gravity) * gravity;//设置跳跃的初始速度,利用匀加速直线运动规律
 
       }
 
    }
 
      PlayCC.Move(motionvalue);//调用Move函数,将motionvalue参数传给Move
 
      if (animatorcontroller)
    {
           animatorcontroller.movespeed = movespeed * v;
           animatorcontroller.alerted = v == 0 ? false:true;
    }
 }

具体参数显示如下:

 

 

这里把GroundCheckPoint赋给了CheckPoint公有变量。

<补>

Physics.CheckSphere():
如果有任何碰撞体与世界坐标系中由 position 和 radius 界定的球体重叠,则返回 true。
 
参数:
position 球体的中心。
radius 球体的半径。
layerMask 层遮罩,用于在投射胶囊体时有选择地忽略碰撞体。
queryTriggerInteraction
指定该查询是否应该命中触发器。
 
注意这里的层遮罩,我们将地面(groundfloor)的Layer设置为ground,从而该函数调用时只检测到地面碰撞体进行触发.

 

推荐阅读