How could I move an object, while respecting the gravity and other related physics in Unity?
I tried using the following approach:
void FixedUpdate()
{
rigidBodyToMove.velocity = velocity;
}
The problem with that approach is, for example, when the object falls from a height there is no acceleration of a fall. Also, I am sure that there are other physics related things which do not get respected with that approach.
So, I tried using this:
void FixedUpdate()
{
rigidBodyToMove.AddForce(force);
}
Now the problem with this approach is that, for example, when moving horizontally the object gets acceleration, while I want to just move it.
So, my question is basically how could I move an object (in my case a character, using an input from user), while respecting all the physics. I kind of want to have various physical forces which act on the object (gravity, wind, collisions...) but then I want my movement input to not act like a physical force but instead act like a constant velocity layered on top of all the physical movement.
UPDATE
There are four ways I know how to change the velocity (neither of them suits me, hence the reason for this question being posted):
1 Change velocity each frame by setting it:
rigidBodyToMove.velocity = velocity;
It is not appropriate for me, because this way velocity stays constant and ignores physics accelerations (e.g. gravity acceleration during a fall).
2 Change velocity each frame by incrementing it:
rigidBodyToMove.velocity += velocity;
This approach does not suit me either, because now I will add acceleration. Between the first increment and the second increment the
rigidBodyToMove.velocity
decreases and for sure needs to be incremented by some value to remain a constant movement force, but it may decrease or increase by a greater absolute value than the value of the velocity
.
3 Change the velocity only once. This does not work as well, because the next frame Unity will recompute velocity and I will lose my applied movement force. And also I am losing the physcis forces with this approach.
4 Increment the velocity only once. Similar to 3, Unity will recompute the velocity and I will lose my movement force the next frame.
UPDATE 2
I tried to use the following approach : rigidBodyToMove.MovePosition(rigidBodyToMove.position + velocity*Time.deltaTime);
The effect was exactly the same as in the 1 above. I.e. e.g. during a fall if I will start moving the fall acceleration disappears.