Enemy Knockback

Greetings!

How would I go about to create a knock-back from an enemy that sends the player flying in the correct direction?

I already figured out how to push the player in the correct x-direction:

	Vector2 myPosition = transform.position;
	Vector2 dir =  myPosition - enemyPos;
	dir.y = 0;
	
	rigidbody2D.AddForce(dir.normalized * force);

If I want to push the player a greater distance in the x-axis, I have to crank up the force variable to about 1500 which makes the player almost teleport, so I figured a bit of force in the y-axis would make the character fly further.

I’m kind of looking to create a knock-back like in this image

32965-dump.png

Thanks for your help!

If you first change dir.y and then normalize, you might get wildly inconsistent results depending on what the dir.x value was. (The end result of normalizing (2f, 0.5f) and normalizing (0.1f, 0.5f) is very different)

It might help a little if you do it in different order.

    Vector2 dir =  (myPosition - enemyPos).normalized;
    dir.y = 0.5;
 
    rigidbody2D.AddForce(dir * force);

And then find a suitable dir.y

Still the root of the problem is deciding what you want to happen in each situation mathematically and what are all the possible use cases.

Since you are not using the magnitude of the dir distance vector for anything (you are normalizing it), you might as well type in some vector that gives you the desired trajectory and just flip the x-coordinate based on which side the enemy is on.

Vector2 pushForce = new Vector2(100, 50);

if (myPosition.x > enemyPos.x)
{
   pushForce.x = -pushForce.x;
}

rigidbody2D.AddForce(pushForce);