Home > Enterprise >  Unity 2D how to delay jump
Unity 2D how to delay jump

Time:11-09

I am in Unity 2D and I need to delay the jump, because right now you can just spam jump, which shouldn't happen, it is not good for a platformer. Here is my whole movement script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMove : MonoBehaviour
{
    public Vector2 speed = new Vector2(15, 15);

    // Update is called once per frame
    void Update()
    {
        float inputX = Input.GetAxis("Horizontal");
        float inputY = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(speed.x * inputX, speed.y * inputY, 0);

        movement *= Time.deltaTime;

        transform.Translate(movement);
    }
}

I lowered the speed from 50 to 15, I expected if you couldn't jump as high you wouldn't be able to spam, couldn't move up as high too quickly, but you could still spam jump.

CodePudding user response:

Use a collider at the bottom of player object and check if it collides with ground object. Add tag to ground object called ground.

Add bool grounded to your script, use OnCollisionEnter2D and check for collisions with tag ground. Like this :

Private Void OnCollisionEnter2D(Collision other){
if(other.tag == "ground") grounded = true;
else grounded = false;

}

and just limit your inputY by that bool

if(grounded) float inputY = Input.GetAxis("Vertical");

Also it is better to make make all variables out of Update function like you did with Vector2 speed

Hope this helps!

CodePudding user response:

You need to ground check before making the player jump. There are many ways to do it, but using a boxcast works most of the time. You can check out this Video tutorial on Ground check in Unity.

  • Related