RigidBody2D.AddForce() horizontally is not working!
Hello all, I am having trouble with AddForce horizontally, for some reason my player would be teleporting a set distance instead of actually being "pushed." I have searched the forums and have tried out multiple solutions but none of them work. I am currently making a 2D game, and the method I am working on is when the player takes damage, it will get knocked back.
void takeDamage(float value)
{
health -= value;
Vector2 move = new Vector2(rb2D.velocity.x + 20f,rb2D.velocity.y + 2f);
rb2D.AddForce(move*2f, ForceMode2D.Impulse);
}
I have tried changing the ForceMode2D to both Impulse and Force but it does not work. I've also tried changing the velocity of the player instead of adding force but it also does not work. The strange thing is the vertical portion of the knockback works, it will get pushed up, but teleport sideways. It works like this when I add velocity and add force. If anyone could help I would gladly appreciate it.
Answer by sunnykwong91500 · Mar 25, 2018 at 12:24 AM
Ok so the problem I found was that I kept on setting the velocity of my player to 0 in my moveHorizontal() method. Since this is called in fixedUpdate() it occurs repetitively by setting the float move to 0 and then setting to velocity to 0. So for anyone who has any trouble with this, cause I've seen a lot of posts about this, make sure you are not setting the velocity of the player to 0 at any other point.
"Where else in your code do you move your player horizontally? The issue is probably caused somewhere else."
Gee, not like my answer led you to solve it. Lol
Answer by exzizt · Mar 24, 2018 at 04:31 AM
You say that vertically works great, but horizontally is "teleporting". Maybe this is because for the vertical you are adding 2, but for the horizontal, you are adding 20. Is this a typo? Try 2 instead.
I've tried multiple different values, all it does is just increase the distance that it teleports.
Try move.normalized * 2f ins$$anonymous$$d.
move.normalized *2f made it so that the player barely moved at all. That removed the vertical portion and the horizontal movement moved only a tiny bit.