0
\$\begingroup\$

I am making a 3D basic runner game, where my character constantly "runs" in a constant pace. At first I used MovePosition() to implement the movement behavior, but I encountered a weird behavior while colliding with other rigidbodys, especially dynamic rigidbodys. So I tried using AddForce() instead -

Vector3 desiredVelocity = new Vector3((transform.forward.normalized.x * playerSpeed), 0f, 0f);
rb.AddForce(desiredVelocity - rb.velocity, ForceMode.VelocityChange);

The collisions behave fine now, but I'm having issues with the gravity - With this implementation, the rigidbody gets "pushed" forward and the bigger the force added to it, the lower gravity gets, and it becomes kind of a trade-off, where increasing gravity makes the player "slower" and increasing the force added makes the gravity effect lower. Pretty intuitive physics issue.

I'm not sure if there's a simple solution for this physics issue or should I approach it differently. What would be the proper, standard implementation for this kind of movement?

Thank you in advance, Omer

\$\endgroup\$
1
\$\begingroup\$

Because you're forcing your velocity to match your input value each frame, you're stopping gravity from accumulating into a large downward velocity. Each physics step, the object has to start falling from what's effectively the peak of its arc, never getting to the fast portion of the downward arc.

If your running push is meant to be only horizontal, and your gravity is vertical, you can solve this by just zeroing out your velocity change on the y axis:

Vector3 desiredVelocity = new Vector3(playerSpeed, 0f, 0f);
Vector3 velocityChange = desiredVelocity - rb.velocity;

velocityChange.y = 0f;

rb.AddForce(velocityChange, ForceMode.VelocityChange);
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.