- Home /
Addforce increases the object's speed overtime
I am trying to addforce to an object to let it constantly move to the right on a fixed speed. But when I try it with the following code, the speed starts slowly and starts adding up and going very fast over time. How can I keep the speed to be constant without adding on.
I do not want it to start slowly. I want it to immediately react to the speed and keep to the same speed through out.
I am trying to use AddForce instead of switching to manipulating velocity directly. Please advice what I am doing wrong.
public float speed = 15;
Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
rb.AddForce(Vector2.right * speed * Time.deltaTime);
}
Answer by CodeElemental · Apr 12, 2015 at 12:51 AM
You could use
rb.velocity = new Vector2(direction * speed * Time.deltaTime, rb.velocity.y);
I have another AddForce which controls the jump as follows. Directly adding velocity this way going to affect that portion.
rb.AddForce(Vector2.up * jumpSpeed);
Then you need to preserve the Y component of the velocity and only affect the horizontal one.
direction = 1; // for left put -1;
rb.velocity = new Vector2(direction * speed * Time.deltaTime, rb.velocity.y);
New vector2 only takes in no parameters or 2 floats which are essentially the x and y numbers. How are you adding that velocity.y at the end. Is it a variable you declared? Cos its says to me "'velocity' does not exist in current context".
Fixed it, sorry. The Y component should be the original one (from the rigidbody object).
Answer by Limesta · Apr 12, 2015 at 05:15 PM
Something you can attempt is to give your object a jolt of speed at the beginning and then add force over time afterwards I would do this_>
if (rb.velocity < 10)
{rb.AddForce(Vector2.right * speed, forcemode2d.Impulse);}
else
{
rb.AddForce(Vector2.right * speed * Time.deltaTime);
}
that 20 can be changed to whatever you want your threshold to be.
So if your velocity is under 10, give it a large speed boost, after that just add a minor amount of force
Your answer
![](https://koobas.hobune.stream/wayback/20220613192840im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to set multiple android name in one android manifest?? 0 Answers
Automatic Network Migration Manager 0 Answers
Android build misbehaving. 1 Answer
Incorrect velocity after collision 1 Answer