Saber
Saber

Reputation: 23

How to jump smoothly in Unity3D

I add a CharacterController to Player.But when I test the jump function,I find that the Player will move upwards immediately.

    if (Player.isGrounded) 
    {
        if (jump) 
        {
            Move.y = JumpSpeed;
            jump = false;
            Player.Move (Move * Time.deltaTime);
        }
    }
    Move += Physics.gravity * Time.deltaTime * 4f;
    Player.Move (Move * Time.fixedDeltaTime);`

Upvotes: 2

Views: 12162

Answers (1)

Umair M
Umair M

Reputation: 10720

  1. You are calling Player.Move() twice in one frame. This might be an issue.
  2. You are adding gravity to Move vector, which means it will always go upward when you call this code.
  3. naming a variable like Move is not a good convention. It creates confusion while reading because there is already a method of same name. change it to moveDirection.

Here is sample code:

public class ExampleClass : MonoBehaviour {
    public float speed = 6.0F;
    public float jumpSpeed = 8.0F;
    public float gravity = 20.0F;
    private Vector3 moveDirection = Vector3.zero;
    CharacterController controller;
    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    void Update() {
        if (controller.isGrounded) {
            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
            moveDirection = transform.TransformDirection(moveDirection);
            moveDirection *= speed;
            if (Input.GetButton("Jump"))
                moveDirection.y = jumpSpeed;

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

hope this helps.

Upvotes: 5

Related Questions