Zaxoosh
Zaxoosh

Reputation: 167

Player Movement In Unity With Smoother Jumping

I've seen people say that you should set a delay timer right after the walking of a platform or just before you touch the floor because this makes your game feel so much better! Here's the code I've tried previously -

 using UnityEngine;
 using System.Collections;

 public class example : MonoBehaviour {
     //Variables
     public float speed = 6.0F;
     public float jumpSpeed = 8.0F; 
     public float gravity = 20.0F;
     private Vector3 moveDirection = Vector3.zero;

     void Update() {
         CharacterController controller = GetComponent<CharacterController>();
         // is the controller on the ground?
         if (controller.isGrounded) {
             //Feed moveDirection with input.
             moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
             moveDirection = transform.TransformDirection(moveDirection);
             //Multiply it by speed.
             moveDirection *= speed;
             //Jumping
             if (Input.GetButton("Jump"))
                 moveDirection.y = jumpSpeed;

         }
         //Applying gravity to the controller
         moveDirection.y -= gravity * Time.deltaTime;
         //Making the character move
         controller.Move(moveDirection * Time.deltaTime);
     }
 }

Upvotes: 1

Views: 1089

Answers (1)

Antoine
Antoine

Reputation: 141

If you want to make the player jump right before you touch the ground, just use a timer that automatically counts down. Change it so that you don't jump if you press the jump button, but you instead reset the timer. Here is an example:

public float jumpRememberTime = 0.2f; 
private float jumpRememberTimer; 

private void Update()
{
    jumpRememberTimer -= Time.deltaTime; 

    if (Input.GetButtonDown ("Jump"))   
        jumpRememberTimer = jumpRememberTime; 

    if (jumpRememberTimer > 0f && controller.isGrounded)
    {
        moveDirection.y = jumpSpeed; // jump
    }
}

For allowing the player to jump right after they leave a platform you also need a timer. This is called coyote time. You use a timer and make it count down once the player has left the platform. This is the code after implementing this.

public float jumpRememberTime = 0.2f; 
private float jumpRememberTimer; 

public float groundedRememberTime = 0.2f; 
private float groundedRememberTimer = 0f;

private void Update()
{
    jumpRememberTimer -= Time.deltaTime; 

    if (Input.GetButtonDown ("Jump"))   
        jumpRememberTimer = jumpRememberTime; 

    if (isGrounded)
        groundedRememberTimer = groundedRememberTime; 
    else
        groundedRememberTimer -= Time.deltaTime; 

    if (jumpRememberTimer > 0f && groundedRememberTimer > 0f)
    {
        moveDirection.y = jumpSpeed; // jump
    }
}

Upvotes: 1

Related Questions