简体   繁体   中英

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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