Skip to content

Instantly share code, notes, and snippets.

@harryrook
Created May 23, 2022 21:54
Show Gist options
  • Save harryrook/4377c01af04327607f2ba8eb5620150f to your computer and use it in GitHub Desktop.
Save harryrook/4377c01af04327607f2ba8eb5620150f to your computer and use it in GitHub Desktop.
A simple 2d player jump script for Unity 2D
//force the player jumps at
public float jumpForce;
//bool to check if player is on the gorund
public bool grounded;
//reference to the player rigid body 2D
public Rigidbody2D playerBody;
// Start is called before the first frame update
void Start()
{
//get reference to players Rigidbody2D component
playerBody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
//check if the space key is tapped and if player is on the ground
if (Input.GetKeyDown(KeyCode.Space) && grounded) //makes player jump
{
//player jumps
playerBody.velocity = new Vector2(playerBody.velocity.x, jumpForce);
}
}
//Check if player is on the ground
private void OnTriggerEnter2D(Collider2D collision)
{
//check if the collsion is happening with a game object with "ground" tag.
if (collision.CompareTag("ground")){
grounded = true;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
//check if the collsion is happening with a game object with "ground" tag.
if (collision.CompareTag("ground")){
grounded = false;
}
}
@ThQWERTY
Copy link

Why does this not work?

@harryrook
Copy link
Author

Why does this not work?

In my game or yours? Without more context on what you are trying to do I'm afraid I'm not sure why it might not be working.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment