Jump Ability in my first game (2d platformer)
Can anybody tell me why this code isn't working? I don't get any errors, nothing happens when I press space. I am a beginner so please explain your answer. Thanks. Here is my code:
public class AbilityJump : MonoBehaviour {
public float jumpHeight;
private bool isJumping;
private Rigidbody2D RB2D;
private void Awake ()
{
RB2D = GetComponent<Rigidbody2D> ();
}
private void Update ()
{
if (Input.GetKeyDown (KeyCode.Space) && isJumping)
{
RB2D.AddForce (Vector2.up * jumpHeight);
isJumping = true;
}
}
private void OnCollision2D (Collision col)
{
if (col.gameObject.tag == "ground") // GameObject is a type, gameObject is the property
{
isJumping = false;
}
}
}
Answer by Alanisaac · Jan 30, 2018 at 12:05 AM
In your Update
method I think you want your if statement to have the condition !isJumping rather than isJumping. Here's why:
The isJumping variable is a boolean, which has a default of false.
When you check isJumping in
Update
, it is still false, so the code inside theif
is not executed.But the code inside the
if
is the only thing in your script that would ever make isJumping true.
I think you mean !isJumping so you don't end up adding more and more force while the player is in the air. As in:
public class AbilityJump : MonoBehaviour {
public float jumpHeight;
private bool isJumping;
private Rigidbody2D RB2D;
private void Awake ()
{
RB2D = GetComponent<Rigidbody2D> ();
}
private void Update ()
{
if (Input.GetKeyDown (KeyCode.Space) && !isJumping)
{
RB2D.AddForce (Vector2.up * jumpHeight);
isJumping = true;
}
}
private void OnCollision2D (Collision col)
{
if (col.gameObject.tag == "ground") // GameObject is a type, gameObject is the property
{
isJumping = false;
}
}
}
Thanks for the reply. You were right. But now I have the issue that I can jump once, but it seems like isJumping is never being set to false so I can jump again. Do you have any ideas as to why.
Your answer
Follow this Question
Related Questions
Jump Force gets added up with repeated input and causes character to fly off 0 Answers
Help.. Jump by Addforce , could you help me? I want my player jump by addforce 1 Answer
Confused about how AddForce works 1 Answer
rigidBody.addforce doens't work like i want it to 1 Answer
Input.GetButtonDown("Jump") doesn't work 0 Answers