Hi. Im making a 2d platform game and right now im working on HandleHit mechanics. So, if player collides with trigger collider on Enemy, I want him to “impulse” away. Im doing rb.AddForce but it only adds force in y, not in x. I tried various things and nothing seems to work.
That should work, but there are several things that could go wrong here. First, try doing this. Use a vector3 force on it, like this:
rb.AddForce(new Vector3(2, 2, 0), ForceMode.Impulse);
Your player might be travelling along the wrong axis when you are adding force, so using a 3D vector allows you to control the direction of the force more precisely. For example, if your project has x as down instead of z, then this will work.
Secondly, make sure that the player isn’t running into anything. The addforce works in my case, so it could be that the player is getting force added in the x axis, it’s just running into something and losing all of that force immediately.
Third, I suggest using something that flings the player away from the enemy specifically rather than in the direction up and right. The enemy attacks from up and to the right and you’ll just go flying back into him.
I hope some of this helps or clears stuff up for you!
@notpresident35
Thanks for the answer! Sadly, none of these things helped me.
I tried various combinations with Vector3 but again, only works in y axis.
FIXED:
In PlayerController script, change everything that changes velocity directly. For moving around I had code //rb.velocity = new Vector2(horizontal * movSpeed, rb.velocity.y);
instead, use AddForce everywhere you want to change velocity.
If there is an animator attached to the object also make sure that ‘Apply Root Motion’ is not checked - or the animator will try to control the movement.