1
\$\begingroup\$

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?

\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$
    – DMGregory
    Feb 14 at 15:42

2 Answers 2

1
\$\begingroup\$

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!

\$\endgroup\$
1
  • \$\begingroup\$ 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; \$\endgroup\$
    – DMGregory
    Feb 15 at 0:33
0
\$\begingroup\$

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;
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .