I made a code that my 2d character jump, but it keeps going up and idk how to fix this. I need my character to jump once and fall to the ground.

using UnityEngine;

public class playermovement : MonoBehaviour
{

Vector2 moveForward;
 bool canGoForward = true;
 bool canGoOtherDirection;

 void Update () {
     if (canGoForward) { 
         moveForward = gameObject.transform.position;    //When the game starts it will start to go to the right
         moveForward.x += 0.03f;
         gameObject.transform.position = moveForward;  
     }
     if (canGoOtherDirection) 
     {
         moveForward.y += 0.01f;
         gameObject.transform.position = moveForward;
     }
         
     if (Input.GetMouseButtonDown(0)) //When space is pressed, it will start to go up
     {
         canGoForward = false;
         canGoOtherDirection = true;
     }

 }

}

Hi,

I like to use the Rigidbody2D component and the isGrounded technique. Here are the relevant snippets of a basic example. This isn’t working, complete code; just to give you an idea of the concept:

    [SerializeField] private float speed, jumpSpeed; 
    private Rigidbody2D rb;
    private Animator animator;


    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        col = GetComponent<Collider2D>();
        animator = GetComponent<Animator>();

    }

    void Update()
    {
        Move();
        SetAnimationState();

    }

    private void Move()
    {
        // Read the movement value
        float movementInput = playerActionControls.Land.Move.ReadValue<float>();

        // Move the player
        Vector3 currentPosition = transform.position;
        currentPosition.x += movementInput * speed * Time.deltaTime;
        transform.position = currentPosition;
    }
   
    private void Jump()
    {
        if (IsGrounded())
        {
            rb.AddForce(new Vector2(0, jumpSpeed), ForceMode2D.Impulse);
        }
    }

    private bool IsGrounded()
    {     
        // Basic "Is allowed to jump" logic. This just allows a jump action if the chacter is not already moving up - works for this game though
        if (rb.velocity.y > -0.5 && rb.velocity.y < 0.5)
        {
            return true;
        }
        else
        {
            return false;
        }
    }