how to make player jump unity 2d
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class example : MonoBehaviour
{ // **** ALSO HAS CODE FOR PREVENTING MULTIPLE JUMPS ****
public float jumpHeight = 1; // the Height you want the Player to Jump
Rigidbody2D myrb; // To access the Rigidbody Component
bool isGrounded; // to check if player is on the Ground or not to Prevent from jumping more than once
void Start()
{
myrb = GetComponent<Rigidbody2D>();
}
void Update()
{
// basically telling that if player is touching the ground,then allow player to Jump, if not, Don't allow Jumping
if (isGrounded && myrb.velocity.y <= 0)
{
if (Input.GetButtonDown("Jump"))
{
myrb.velocity = new Vector2(myrb.velocity.x, 1 * jumpHeight);
}
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.CompareTag("yourGroundsTagnamehere"))
{
isGrounded = true;
}
}
private void OnCollisionExit2D(Collision2D collision)
{
isGrounded = false;
}
}