- Home /
Why does Gravity (Physics2D) produce different results for AddForce() versus velocity in player sprite?
Why does Gravity in Physics2D engine for Unity2D act different when these two following lines of codes are implemented alternately?
For example, I have attached to my player sprite a Player Controller C# script:
private float speed = 500f;
RigidBody2D playerChar = null;
And then to make my character walk:
Vector2 vec = new Vector2 (Input.GetAxis("Horizontal"), 0);
playerChar.AddForce(vec * speed);
And the Gravity is set to 50
Result 1: My character avatar falls down normally.
Meanwhile when I do:
Vector2 vec = new Vector2 (Input.GetAxis("Horizontal"), 0);
playerChar.velocity = (vec * speed);
And the Gravity is still set to 50
Result 2: My character now takes a long time to fall (it slowly "floats" down).
Why is that?
Answer by Nikaas · Dec 18, 2017 at 09:59 AM
Without having all the information I assume the cause is that the code is re-applied multiple times. So in the second example the vertical velocity is periodically reset to 0, while in the first example the force adds velocity on top of the current velocity.
===
AddForce adds velocity on top the current one (sidenote: AddForce's effect strenght depends on mass).
While velocity property replaces/resets current velocity to the one that's passed.
Answer by aurelioprovedo · Dec 18, 2017 at 10:20 AM
In Result 2, you are setting the horizontal velocity AND the vertical velocity. Since the vertical velocity that you are providing is zero, it is stopping the object every frame.
Change your input code to this: float horiz = Input.GetAxis("Horizontal");
Your answer
Follow this Question
Related Questions
Trying to limit air velocity 2 Answers
Problem of gravity 1 Answer
Jumping a specific height using Velocity & Gravity 1 Answer