- Home /
2D Jump using "Rigidbody2D.AddForce" doesn't work.
I am embarrassed to ask this question, because it's too easy and I'm disappointed in myself that I actually got stuck on this. My simple 2D jump script doesn't work, specifically the Rigidbody2D.AddForce() line is the problem. Here's the code:
public Rigidbody2D rb;
public float jumpHeight = 10f;
public bool canJump = false;
void Awake()
{
rb = gameObject.GetComponent<Rigidbody2D>();
}
void Update()
{
if (Input.GetButtonDown("Jump") && canJump == true && rb != null)
{
//rb.velocity = Vector2.up * jumpHeight;
//rb.AddForce(new Vector2(0f, jumpHeight), ForceMode2D.Impulse);
rb.AddForce(Vector2.up * jumpHeight * Time.deltaTime);
Debug.Log("This Debug.Log line actually gets written in the console, so the problem is not with the if statement.");
}
}
Here are my Rigidbody2D settings:
To clarify, the comment-ed lines at:
//rb.velocity = Vector2.up * jumpHeight;
//rb.AddForce(new Vector2(0f, jumpHeight), ForceMode2D.Impulse);
rb.AddForce(Vector2.up * jumpHeight * Time.deltaTime);
is every solution I have tried up to this point.
Answer by KarMa_PlaYzz · Jul 21, 2021 at 06:57 AM
Have you tried:
rb.AddForce(Vector2.up * jumpHeight);
By doing rb.AddForce(Vector2.up * jumpHeight * Time.deltaTime);
you're trying to do it overtime, but since you only check for Input.GetButtonDown("Jump")
it only registers it for a frame, which doesn't let it run over time.
If this didn't solve your problem; make sure to read the documentation about Rigidbody2D.AddForce()
Hope this helped!
Your answer
Follow this Question
Related Questions
Rigidbody2D.velocity.x not working but Y does 0 Answers
Knockback effect in 2D. 1 Answer
Player Bump on map border 0 Answers
Using direction and Rigidbody2D.AddForce() to move towards object. 1 Answer