- Home /
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));
Are you using this in update? Because if that's the case then you are adding force each frame resulting in constant speed increase
Answer by ModLunar · Sep 20, 2018 at 11:13 AM
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.)
Answer by SkaredCreations · Sep 20, 2018 at 09:51 AM
Instead of adding force it'll be easier if you update directly the velocity of the rigidbody.
Your answer
Follow this Question
Related Questions
Why do my objects keep changing speed? 1 Answer
Pushing and object up/down/left/right at constant speed 0 Answers
Slow down Rigidbody's speed to a stop 2 Answers
Object position question... 0 Answers