Hey everyone,
My problem is that when trying to knock the player back using Impulse AddForce, the player's input overbears the force added.
----------
To better explain the problem, imagine the player holding right arrow to run right. While running right, the character hits an enemy that should knock it back.
Instead of getting knocked back, the character keeps moving right.
That is because for a split-second after the AddForce is called, the character still detects that it is grounded, and therefore the player is still "allowed" to move the character by pressing right arrow.
----------
If I take away the ability to control the character once it got hit, it works fine because even if the character detects that it is grounded, it still can't move. (But it feels wrong solving it this way)
----------
Any insights on how to solve this?
----------
Code:
private void Update()
{
dirX = Input.GetAxisRaw("Horizontal");
if (IsGrounded()&&!disabled)
{
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
}
}
public void KnockBack()
{
float direction;
if (m_FacingRight) direction = -1;
else direction = 1;
disabled = true;
rb.velocity = Vector3.zero;
rb.AddForce(new Vector2(direction * 5f, 5f), ForceMode2D.Impulse);
StartCoroutine(Test());
}
IEnumerator Test()
{
yield return new WaitForSeconds(0.25f);
disabled = false;
}
↧