give me code for unity jumping in csharp

Here is a simple example of how you can make your player jump in Unity using C#:

main.cs
public class Player : MonoBehaviour
{
    public float jumpForce = 10f; // how high the player jumps
    public Rigidbody2D rb; // reference to the player's Rigidbody2D component

    private bool isGrounded = false; // whether the player is touching the ground

    void Update()
    {
        // check if the player is ready to jump
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
        {
            // apply a vertical force that makes the player jump
            rb.velocity = new Vector2(rb.velocity.x, jumpForce);
            // player is no longer touching the ground
            isGrounded = false;
        }
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        // check if the player touches the ground
        if (collision.contacts[0].normal.y > 0.5f)
        {
            isGrounded = true;
        }
    }
}
855 chars
29 lines

In this script, we have a public jumpForce variable that determines how high the player will jump. We also have a reference to the player's Rigidbody2D component.

In the Update function, we are checking if the player is ready to jump by detecting when the space bar is pressed and the player is touching the ground. When the player is ready to jump, we apply a vertical force to the player's Rigidbody2D component and set isGrounded to false.

In the OnCollisionEnter2D function, we detect when the player touches the ground. If the contact normal is pointing upwards (i.e. the player is landing on the ground), we set isGrounded to true.

gistlibby LogSnag