- Home /
Difficulty implementing knockback in a 2D platformer
I'm currently trying to write a script that knocks the player back when they collide with an enemy, similar to the NES Castlevania games. I'm using the Rigidbody.AddForce method and the only time it works as intended is when the player character is standing still. If the player is in motion, the force isn't strong enough to knock the player backwards but I don't want to set knockbackForce too high, otherwise the player will be sent flying back when stationary. Could anyone offer an idea into an alternative way to implement this so that there is a consistent distance the player moves when knocked back? Should I set the player's velocity to zero before applying the force? Below is the method where I use AddForce.
public virtual void TakeDamage() { animator.SetTrigger("Hurt");
if (facingRight)
rb.AddForce((Vector2.left + Vector2.up) * knockbackForce, ForceMode2D.Impulse);
else
rb.AddForce((Vector2.right + Vector2.up) * knockbackForce, ForceMode2D.Impulse);
}
Setting the velocity directly isnt recommended, but you could add a force to the object to make the velocity 0, and after that add your knockback force? Something like: rb.AddForce(rb.mass * -rb.velocity, ForceMode.Impulse)
Answer by astraunotboy · Dec 07, 2021 at 08:29 AM
what about this:
rb.AddForce((Vector2.left + Vector2.up) * knockbackForce + rb.velocity.x, ForceMode2D.Impulse);
Your answer

Follow this Question
Related Questions
Trouble creating knockback when setting velocity on RigidBody2D 0 Answers
Knockback effect in 2D. 1 Answer
Adding knockback to a 2D game (in C#) 2 Answers