'Hold space bar and jump?
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("Jump"))
{
Debug.Log("IS JUMPING");
_rigidBody.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse);
}
}
This is the IsGrounded Code:
private bool IsGrounded()
{
RaycastHit2D raycastHid2d = Physics2D.BoxCast(boxCollider2d.bounds.center, boxCollider2d.bounds.size, 0f, Vector2.down, .1f, layerMask);
//Debug.Log(raycastHid2d.collider);
return raycastHid2d.collider != null;
}
Solution 1:[1]
As said the issue is most probably that the rigibody doesn't move far enough away from the ground immediately so you might get multiple input frames before IsGrounded returns false.
In general for physics related things you should rather use FixedUdpate.
While Update is executed every frame, FixedUpdate uses a fixed time delta => There might be multiple Update calls before he physics are actually applied and your scene is updated accordingly!
While you will want to get one time event input (GetKeyDown) still in Update (otherwise you might miss it) I would move continuous user input into FixedUpdate
[Serializefield] Rigidbody2D rigidbody;
private void Awake()
{
if(!rigidbody) rigidbody = GetComponent<Rigigbody2D>();
}
private void FixedUpdate()
{
rigidbody.velocity = new Vector2(movementSpeed, rigidbody.velocity.y);
if (IsGrounded() && Input.GetKey("Jump"))
{
Debug.Log("IS JUMPING");
rigidbody.AddForce(Vector2.up * jumpForce), ForceMode2D.Impulse);
}
}
And as said just to be super sure you could still add some cooldown like e.g.
private float timer;
public float jumpCooldown = 0.1f;
private void FixedUpdate()
{
rigidbody.velocity = new Vector2(movementSpeed, rigidbody.velocity.y);
timer += Time.deltaTime;
if(timer < jumpCooldown) return;
if (IsGrounded() && Input.GetKey("Jump"))
{
Debug.Log("IS JUMPING");
rigidbody.AddForce(Vector2.up * jumpForce), ForceMode2D.Impulse);
timer = 0f;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
