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.
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.
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 had this problem. Where my player would either be launched off or would barely move.
So to fix it instead of adding an impulse to the object (since I am struggling with the game physics), I have emulated that behavior using transformations. After a time delay the object’s position is offset by a certain amount. This way the motion can be controlled by the time stamps and the distance that it is being offset by.