- Home /
Hold space bar and jump [2D]
So my problem here is that when the player holds the space button the addForce function is increased which I don't want.
So what I want is that if a player holds the space button they can keep jumping continuously if they're on the ground...
Here is my code:
private void Update()
{
GetComponent<Rigidbody2D>().velocity = new Vector2(1.0f * movementSpeed, GetComponent<Rigidbody2D>().velocity.y);
if (IsGrounded() && Input.GetKey(KeyCode.Space))
{
Debug.Log("IS JUMPING");
_rigidBody.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse);
}
}
What do you mean by "the addForce function is increased" ? Also, is there a reason why you use both
GetComponent()
and
_rigidBody
? GetComponent() is an expensive function, if you already have reference with _rigidbody you should consider sticking to it.
Finally, i wonder if your velocity modification does messup with you AddForce() ? Seems like a weird thing to do to manipulate the velocity of your rigidbody like this. Maybe moving the Transform.position.x would be cleaner (and easier to work with) ?
Answer by deceptive_games · Feb 24 at 03:51 PM
Input.GetKeyDown(KeyCode.Space)
This is the opposite of what OP is requesting :
So what I want is that if a player holds the space button they can keep jumping continuously if they're on the ground...
From documentation :
Returns true during the frame the user starts pressing down the key identified by name.
Answer by RehanSanish · Feb 24 at 05:30 PM
If the player already is in the air, go to it's Rigidbody2D and set the gravity scale to 0. Hope this works.
Your answer