Created
May 23, 2022 21:54
-
-
Save harryrook/4377c01af04327607f2ba8eb5620150f to your computer and use it in GitHub Desktop.
A simple 2d player jump script for Unity 2D
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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; | |
} | |
} |
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
Why does this not work?