Help me with knockback please :)

Hi guys! First of all sorry for my english and thanks for read me.
I need help with the knockback.

I’m using this script for the movement :

void Update()
{

if (hp <= 0) return;
float movX;
movX = Input.GetAxis(“Horizontal”);
if (!movement) movX = 0;
anim.SetFloat(“absMovX”, Mathf.Abs(movX));
rb.velocity = new Vector2(velX * movX, rb.velocity.y);
}

And this one for the knockback:
public void EnemyKnockBack(float enemyPosX)
{

float side = Mathf.Sign(enemyPosX - transform.position.x);
rb.AddForce(Vector2.left * side * 30, ForceMode2D.Impulse);

}

BUT I think that it’s not working because im using a rb.velocity script for the movement. And is like the “Addforce” doesn’t exists.

How can I add the “addforce” to my player?

I’m sorry for my english xD but I wish someone could help me… I just need to make a Knockback when enemy touchs me. The other day I changed my movement script, instead using a rb.velocity I used a rb.addforce but that fucks the rest of my code because I made all with rb.velocity and if i change it to rb.addforce i will have so much troubles.

Thanks you so much for read me I hope someone could help me
Greetings!

It’s not working because in your movement script you set velocity on each update.

So when you knockback, you are adding force but it will be replaced by rb.velocity = new Vector2(velX * movX, rb.velocity.y);

I would suggest adding a isKnockback bool to your script, so that you can ignore player movement input during knockback. Then after the knockback you can set the bool back to false.

void Update()
    {

        if (hp <= 0) return;
        if(isKnockback) return; // this is so there is no input during knockback.
         float movX;
          movX = Input.GetAxis("Horizontal");
         if (!movement) movX = 0;
         anim.SetFloat("absMovX", Mathf.Abs(movX));
         rb.velocity = new Vector2(velX * movX, rb.velocity.y);
}

Uhm still not working :confused:

You will need to set isKnockback to be true when it is knockbacked

Okei I Will try later, thanks u for answer me

np, feel free to post the code again if it didn’t work