I'm a very new game developer, and I was making a simple first-person script using AddRelativeForce. However, when I go forward(or any direction), I slowly accelerate instead of going at a constant speed. Does anyone know how to fix this?
-
Consider using a trick like the one shown in this answer. Instead of applying a thrust in your chosen direction as if the character were a space probe firing attitude jets, compute a target velocity (limited by your max speed), then accelerate to match that target. – DMGregory Feb 14 '24 at 15:42
2 Answers
Ok, I found something that works. I basically kept my entire old script, but in every frame I set the velocity to 0 and then added the relative velocity. This caused AddRelativeVelocity
to essentially be the same thing as SetVelocity
, but instead it set the relative force. While this worked in my situation, it might not work in others. Thank you to all of the helpful people who answered my question, though!
-
If you just want to set the velocity, don't add a force, just set the velocity. If you want to make it relative to the object's orientation, just transform the vector first:
body.velocity = body.rotation * localVelocity;
– DMGregory Feb 15 '24 at 00:33
If you want to move your character using the AddRelativeForce-Method you need to keep track of the current velocity to prevent applying a force when the limit is reached. Something like this could be a solution:
public float yourMaximumMovementSpeed = 10f;
// we use velocity.magnitude to get the length of the vector
if (rigidbody.velocity.magnitude < yourMaximumMovementSpeed)
{
rigidybody.AddRelativeForce(yourDirection * yourForce);
}
Instead of adding force you also could just set the velocity directly:
rigidbody.velocity = yourMovementVector * yourMovementSpeed;

- 65
- 4