Search code examples
c#unity-game-enginecharactermove

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

Solution

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