- Home /
Question by
Freewill645 · May 08, 2014 at 11:42 AM ·
horizontal movement
how can i instantly change the the direction of a force and speed aplyd to a 2D object
I am making a 2d sidescroller and i want that if the character changes its direction the speed he is traveling at in 1 direction is also used in the other direction
h = Input.GetAxis("Horizontal");
if(Input.GetKey(KeyCode.LeftArrow))
{
if(h*rigidbody2D.velocity.x < maxSpeed)
{
rigidbody2D.AddForce(new Vector2(Time.deltaTime*speed*(h*rigidbody2D.velocity),0)); }
}
if(Input.GetKey(KeyCode.RightArrow))
{
if(h*rigidbody2D.velocity.x < maxSpeed)
{
rigidbody2D.AddForce(Vector2.right*Time.deltaTime*speed+(h*rigidbody2D.velocity));
}
}
any suggestions on how to do that? thanks in acvance
Comment
Wiki
Answer by hippysniper · May 08, 2014 at 12:42 PM
In stead of imidiatley applying the force to the object you could store the value of the force and apply in which direction you require.
eg
if(Horizontal != 0 && currentSpeed < max speed){
currentSpeed += 0.1 * time.deltatime;
}
rigidbody2D.velocity = new Vector2(currentSpeed * Horizontal,0);
being that Horizontal is from -1 to 1 any value for current force will be applied appropriatley.
i hope it helps
Your answer
![](https://koobas.hobune.stream/wayback/20220613144532im_/https://answers.unity.com/themes/thub/images/avi.jpg)