Help with Knockback

Ey guys first of all sorry for my bad english and thanks you sou much for read me.

I have troubles with knockback, with this code my player only Jump when collider with an enemy

public void EnemyKnockBack(float enemyPosX)
{
jump = true;

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

What i’m doing wrong? My player only jump when the enemy touchs him but I need the knockback!!
Thanks you so much

Hello @Flauros1 ,
So what more exactly happens when you run this code? By the looks of it, it should add an instant force to the GameObject with the Rigidbody2D attached to it, in either positive or negative x axis.

The enemy only jump after this :frowning:

(The enemy jump is on Y, he don’t make the Knockback)

What I usually do when faced with a coding mystery like this, is to break the issue down a bit.
What happens if you create a new GameObject, add a rigidbody2D onto that GameObject, and a script with only that knock back code, being executed on key down or something similar? Does it behave correctly?
Then you can either scale it even further back, or if it works, start adding back the pieces to see when the issue starts to appear again.

Try multiplying a big number and see if it makes any changes.

rb.AddForce(Vector2.left * side * fuerzaSalto * 3000, ForceMode2D.Impulse);

Still not working uhm…

I’m guessing you have a function which moves the character in your fixedUpdate or Update (even tho it shouldn’t be in update) which zeros out the velocity on the x axis.
Just toggle it off when you are knocked back.
You can do it with a bool, state machine or whatever you want.

@Flauros1 , did you try to break the functionality down a bit and test each piece of it? That tends to highlight what causes the issue.

Well I tried this for the Knockback… but only works with Vector2.up
It doesn’t works with vector2.left why? xD

Read my comment again.

For more detailed explaination, here’s the solution to a thread I opened with the same problem a few months ago:
https://discussions.unity.com/t/775110/5