1
votes

I've been looking around the Internet to help set my character's speed to a maximum - basically, putting an upper limit on its horizontal speed. The best thing I've found so far is this:

rb.velocity = new Vector2(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed), rb.velocity.y);

The main issue with this, though, is that this prevents the character's actual velocity from going past whatever maxSpeed is set to (let's say 4), meaning that if, say, it is hit by a moving object that would push it so that its horizontal velocity would go past 4, whenever movement calculations are done, it would be reset to 4. What I am looking for is something that would prevent the character from accelerating on its own past 4 but that would still allow it to move with external force.

1
you should put the clamp on the method you use to move your character. this is just clamping the velocity of the object as a whole.ryeMoss

1 Answers

0
votes

My idea would be to only clamp where you want to actively set the velocity due to user input and if it is not already higher (due to external forces).

something like

if(Mathf.Abs(rb.velocity.x) < maxSpeed)
{
    // calculate your new velocity according to user input
    float newVelX = XYZ;

    // than clamp it
    newVelX = Mathf.Clamp(newVelX, -maxSpeed, maxSpeed);

    // and finally asign the new vel
    rb.velocity = new Vector2(newVelX, rb.velocity.y);
}