in my 2d top down shooter, how do i make it so when you get in contact with an enemy, u get knocked back a little, when i tried it, it didnt work tho, how do i do it so it knocks me back in the direction i came from?
Completely depends on who is moving your character:
You? Then code it as a movement sequence.
Rigidbody? Make a sudden force the way you want.
Something else? …
Probably easiest to check out some tutorials.
Things to watch out for: disabling input during the knockback, otherwise continued input would instantly negate it, so it has to be a controlled temporary disconnection of user inputs.
i added this code
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.CompareTag("Enemy"))
{
Vector2 dir = transform.position - collision.gameObject.transform.position;
canMove = false;
playerRb.AddForce(dir * kb, ForceMode2D.Impulse);
StartCoroutine(KnockbackStunTime(kbStunTime));
}
}
IEnumerator KnockbackStunTime(float cooldown)
{
yield return new WaitForSeconds(cooldown);
canMove = true;
}
how do i make it rly sudden but not push you back so far? when i set the kb to 5, it pushes me the distance i want but it does it too slow, when i make it like 10, which is the speed at which i want it to push me, it pushes me wayyy too far. how do i do this?
Using the physics engine doesn’t always lend itself well to entertaining gameplay or cool “moves”. A lot of the things you see in games or in movies/tv are physically impossible. For example, moving your body 5 meters in half a second and coming to a quick halt might look cool, but in real life in order to accomplish that you would have to apply some pretty extreme forces to your body. First an extreme force to push you back quickly, and then a second extreme force to cut the velocity back to zero.
So your choices are:
- Use the extreme forces required to get the effect you want. This may involve applying multiple forces at different times - for example, a force to push the player back and then another force to slow the player down when they get to the desired distance.
- Abandon physics altogether and go with more traditional direct animation methods.
i kinda want my knockback to be like the enemy knockback in Brackeys’ game, Soul Surge. How do i do this?
Either of the two methods I’ve already described.
im expirementing with the first thing you said, it just creates a rly buggy thing where the player moves back then forward then back then forward, it just results in rly buggy movement, how would u suggest i apply the first method?
btw, i did addforce in one direction then did addforce in the opposite direction
You’ll want to apply what is essentially va “braking” force. It should be against the direction of the current velocity, but never exceeding an amount such that it would result in reversing the direction of motion. At most it should stop the motion. You’ll have to do some math to work that out.