简体   繁体   English

Unity C#-跳跃时移动角色

[英]Unity C# - Move character while jumping

My character moves great, and jumps great. 我的角色移动非常棒,跳跃也很棒。 But when jumping he just moves straight in the direction he came from and you can't rotate or move him while in the air. 但是当他跳跃时,他只会朝着他的方向直线移动,在空中时你不能旋转或移动他。 How can that be done? 那怎么办?

From the Update Function: 从更新功能:

if (controller.isGrounded)
{
    moveD = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
    moveD = transform.TransformDirection(moveD.normalized) * speed;
    moveDA = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));

    if (moveDA.magnitude > 0)
    {                 
        gameObject.transform.GetChild(0).LookAt(gameObject.transform.position + moveDA, Vector3.up);
    }

    if (Input.GetButton("Jump"))
    {
        moveD.y = jumpSpeed;
    }
}

moveD.y = moveD.y - (gravity * Time.deltaTime);
controller.Move(moveD * Time.deltaTime);

controller.isGrounded Is only true if the last time you called controller.Move() the bottom of the object's collider is touching a surface, so in your case once you jump, you cannot move until you hit the ground again. controller.isGrounded仅当上次调用controller.Move()对象碰撞体的底部接触表面是正确的,因此,在这种情况下,一旦跳转,您将无法移动,直到再次触地。

You can solve this by separating your movement code and jumping code like so: 您可以通过分离运动代码和跳跃代码来解决此问题,如下所示:

moveD = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
moveD = transform.TransformDirection(moveD.normalized) * speed;
moveDA = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));

if (moveDA.magnitude > 0) 
{ 
  gameObject.transform.GetChild(0).LookAt(gameObject.transform.position + moveDA, Vector3.up);
}

if (controller.isGrounded)
{
  if (Input.GetButton("Jump"))
  {
    moveD.y = jumpSpeed;
  }
}
moveD.y = moveD.y - (gravity * Time.deltaTime);
controller.Move(moveD * Time.deltaTime);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM