How can I limit the height the player can get when jumping?

Hi! I am currently creating a 2d endless runner game. Similar to chrome’s dino game. I have a mechanic where the longer the player presses space bar, the more powerful the jump power is and the shorter the player presses it, the less powerful the jump power is.

So my problem is how can I limit the height the player can reach when he jumps while maintaining its jump power?

Here is my code:

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

public class playerScript : MonoBehaviour
{
    [SerializeField] private Rigidbody2D playerRb;
    [SerializeField] private Transform groundCheck;
    [SerializeField] private LayerMask groundLayer;

    public float moveSpeed;
    [SerializeField] private float jumpPower;
    private bool hasJumped;
    private bool hasShortJumped;

    void Start()
    {

        playerRb = GetComponent<Rigidbody2D>();
        getGroundCheckTransform();

        hasJumped = false;
        hasShortJumped = false;
    }

    void Update()
    {

        if (Input.GetKeyDown(KeyCode.Space) && isGrounded())
        {
            hasJumped = true;
        }
        if (Input.GetKeyUp(KeyCode.Space) && playerRb.velocity.y > 0f)
        {
            hasShortJumped = true;        }


    }

    private void FixedUpdate()
    {
        playerRun();
        if (hasJumped)
        {
            playerJump();
            hasJumped= false;
        }

        if(hasShortJumped)
        {
            shortPlayerJump();
            hasShortJumped= false;
        }

    }

    private void playerRun()
    {
        playerRb.velocity = new Vector2(moveSpeed, playerRb.velocity.y);
    }

    private bool isGrounded()
    {
        return Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
    }

    private void playerJump()
    {
            playerRb.velocity = new Vector2(playerRb.velocity.x, jumpPower);
    }

    private void shortPlayerJump()
    {
        playerRb.velocity = new Vector2(playerRb.velocity.x, playerRb.velocity.y * 0.5f);
    }

    void getGroundCheckTransform()
    {
        GameObject temp = GameObject.Find("groundCheck");
        if (temp != null)
        {
            groundCheck = temp.transform;
        }
        else
        {
            Debug.Log("Ground Check not found");
        }
    }

}

Two possible ways:

  • put an appropriate collider over the top of the player at the height limit

  • limit the Y component of the position yourself and clamp it if it goes above what you consider the hight limit