- Home /
how to get a constant velocity 2D?
I'm making a game where a 2d player can jump between planets and such, and it's all going great except for one thing. the player has no control while in the air. i have tried adding velocity to it, but that causes the player to fly forward faster and faster. i want the player to be able to move forward a small amount while being pulled to the nearest planet.
this is what i have. i need it to move in the transform.right direction because the player rotates.
H = Input.GetAxis ("Horizontal"); if (Grounded == false){ GetComponent ().velocity += new Vector2(transform.right (airSpeed H)).x,(transform.right (airSpeed H)).y); }
Answer by Teravisor · Jan 25, 2016 at 12:12 AM
Problem is, you're using .velocity += new...
- that means each new step you increase velocity. Remove + there, leave just .velocity = new...
. But this way you need to actually calculate new velocity from previous one.
So for solutions I propose:
First way to remember what velocity you added previous step from input and remove it on next step. It will work like this: during step first subtract previous user input velocity from player velocity then add new input velocity and remember it in variable.
Second way is to limit speed: use
if(GetComponent ().velocity > maxSpeed)
GetComponent ().velocity=GetComponent ().velocity.normalized*maxSpeed;
Might not work how you want with gravity though.
i'm aware that is a problem, but that isn't it. there is a code applying gravity forces to the object, if i set velocity = to something, it will halt it's descent, and i'm not going for that.
@weirdpen I've proposed two ways of solving things. I've edited answer for better formatting as it seems first solution wasn't noticed. I don't think you've read my answer completely.
Your answer
![](https://koobas.hobune.stream/wayback/20220612061545im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Velocity from external objects 0 Answers
Is there a way to lock velocity? 3 Answers
how to jump at fixed height but faster 0 Answers
How to use AddForce and Velocity together 1 Answer
Using child colliders with rigidbodies/joints in 2D 0 Answers