- Home /
Inconsistent Top Speeds On Player
I have this code set up on my player to limit how fast they can go:
private void FixedUpdate()
{
//Moves the player up to top speed. if greater than the top speed, doesnt add force.
if (inputLR > 0 && rb2d.velocity.x < topSpeed)
{
rb2d.AddForce(Vector2.right * inputLR * moveSpeed);
}
else if (inputLR < 0 && rb2d.velocity.x > -topSpeed)
{
rb2d.AddForce(Vector2.right * inputLR * moveSpeed);
}
}
I have used this code on a similar project (in unity 2018.3.9f1) and it worked perfectly for me, allowing me to reach exactly what the top speed is set to no problem. But now, I used that same line of code again (in unity 2019.1.7f1) and I am getting velocities of varying amounts. I have no clue what is going wrong!
If I set the top speed to 12, the player will speed up to a velocity of 11-14 and maintain that velocity until the button is let go. This velocity that it decides to maintain seems completely random.
Is there something I am doing wrong here? Should I just scrap this code and redo it differently?
depending on the size of your force the problem might be the following:
imagine your topspeed is 12, and a portion of your force adds 3 velocity then the following cases might appear: you have v = 9 wich is smaller than 12 and add 3 velocity, -> nice at maxspeed.
but you might also have v = 11.9 and add 3 -> topspeed of 14.9 which is all allowed by your current code. So check 2 with smaller forces if this still occures.
Changing the force applied to my character does nothing except make the difference in top speed smaller, sadly. As I said, I used this exact same code in another project. I used a speed of 55 in that one and it works as intended.
No, this code can never work as you have it intended since it does not enforce any kind of top speed. What your code does is adding a force every frame as long as the current velocity is smaller or equal to your topSpeed value. That means you just stop adding a force once the velocity is larger. At this point the velocity is already larger. How much depends on the amout of force you add. However at no point does this limit the velocity exactly to topSpeed.
Answer by Bunny83 · Jul 03, 2019 at 02:50 AM
If you want to limit the velocity to topSpeed you should just do this in FixedUpdate:
rb2d.velocity = Vector2.ClampMagnitude(rb2d.velocity, topSpeed);
Though if you also want to move on the y axis and don't want to limit the y axis as well, you have to do
Vector2 vel = rb2d.velocity;
vel.x = Mathf.Clamp(vel.x, -topSpeed, topSpeed);
// maybe clamp vel.y in a similar way but with other min and max values?
rb2d.velocity = vel;