how to move an object with constant speed without changing the velocity

lets say i have a 2D scene with a player and a rigidbody on it and i move it left and right by input.
normally i would move the player by changing the velocity in the desired direction.
now the player is maybe near a exploding bomb or gets a hit from an enemy.
then i would Add a Force in a specific direction to simulate that.
in my case the player then receives the force for 1 Frame and then suddenly stops because its velocity is set to the value i gave it for moving the player.
if i try to move the player by adding force to it it would gets faster and faster every frame that the input was pressed and doesnt move instantly because it has a (mass?) so i dont have a constant moving speed.

now how can i move the player with a constant speed and still add forces to him that dont get stopped?
i already googled that but most of the time the solution was a workaround or in java script which i couldnt translate to c# :smile:

if this was already discussed and solved please send me a link.

instead of setting the velocity directly, set a target velocity and create a feedback controller that tries to reach the target velocity.

public float strength = 1f;

Vector2 targetVelocity = new Vector2(yourInputX, yourInputY);
Vector2 currentVelocity = rb.velocity;

rb.AddForce((targetVelocity - currentVelocity) * strength);

Input code goes to Update(), AddForce to FixedUpdate(). The snappier you want the movement to be, the higher “strength” should be. For absurdly high strength, this will get numerically unstable.

It’s called a feedback controller, because you’re not just setting a value (feed forward), but you’re taking the actual situation into account (feedback). That means the output of the system (velocity) is fed back into the input of the system (a force) to follow a set value (your target velocity).

This was discussed probably a brazillian times in every application and by engineering student that has remotely something to do with dynamics, but it’s hard to find if you don’t know what you’re looking for and how stuff is called. Furthermore, it looks intimidating because usually there’s formulae (ugh)

1 Like

tjmaul this was exactly what i was looking for! thank you so much!
i think i should print out your post and frame it for the future :smile: