how to keep speed canstant in flappy bird?

I’m creating flappy bird for learning and when I play bird’s speed is constantly increasing somehow,
How can I fix that?
I’ve used this code :
rb2d.AddForce(new Vector2(speed, 0));

Instead of adding force it’ll be easier if you update directly the velocity of the rigidbody.

Also, if you wanted to use force to do it, in theory, it should work if you calculate the required force each frame to get back to the velocity you want, like this:

Using these 2 equations from physics:

//Newton’s Second Law

F = ma

//Constant acceleration (for a very short amount of time – during FixedUpdate for example)

a = Δv/t

(Substitute Δv/t for a, into the equation F = ma)

F = mΔv / t

So therefore, as an example, if you’re applying this force to the Rigidbody2D in a MonoBehaviour’s FixedUpdate(), it might look like this:

using UnityEngine;

public class YourFlappyBirdScript : MonoBehaviour {
	[SerializeField] private Vector2 targetVelocity;
	private new Rigidbody2D rigidbody;

	public void FixedUpdate() {
		//F = mΔv / t
		Vector2 force = rigidbody.mass * (targetVelocity - rigidbody.velocity) / Time.fixedDeltaTime;
		rigidbody.AddForce(force);
	}
}

Please don’t use that name though for the script, find a better name haha XD. Anyway, notice that for Δv, it’s whatever your “target” velocity is (must be a vector), subtracted by the Rigidbody2D’s current velocity. This is the different from your current velocity to the one you want to get to – that’s exactly the velocity difference you want to change, to get to the targetVelocity.

If you’re using speed, (which that is often times more convenient), just multiple your speed (a float, scalar) with a unit vector (Vector2) for its direction. This will get you your targetVelocity.


And to be honest, I hope this works. Because usually when I inject formulas into the physics engine, it’s often times off for some mysterious reason that refuses to show itself! If it doesn’t, then you can directly set the velocity. (Note that in 3D, Unity recommends not directly setting Rigidbody’s velocity. Instead, use AddForce(…) with ForceMode.VelocityChange.)