0
\$\begingroup\$

im using this code for my 2D TopDown mobile player movement.but when i move player With UI Image buttons player keep moving.it didnt stop.and also player starting of move he is very slow. the he accelerate his speed.how can i fix this.

i add BoxCollider 2D and Rigibody2D my sprite.the set Gravity to 0.

this is my code.

    public class PlayerScript : MonoBehaviour {
public float speed = 150f;
float hInput ;
void FixedUpdate()
{
    Move (hInput);

}

public void Move(float horizontalInput){
    if (horizontalInput.Equals(1)) {
                    rigidbody2D.AddForce (Vector2.right);

    }if (horizontalInput.Equals(2)) {
        rigidbody2D.AddForce (-Vector2.right);
    }if(horizontalInput.Equals(3)) {
        rigidbody2D.AddForce (Vector2.up);
    }
    if(horizontalInput.Equals(4)) {
        rigidbody2D.AddForce (-Vector2.up);
    }
    }

    public void StartMoving(float horizontalInput){
    hInput = horizontalInput;
    }
    }
\$\endgroup\$
1
\$\begingroup\$

It does not stop, if you don't have friction and gravity, that in normal world slow you down. When applying force, you are really not adding force at all and in fact i am bit surprised that it actually moves at all.

You should apply more force, to get your object moving. Try something like this.

  • Vector2.right = Thats the direction of the force
  • Multiply by speed = takes your wanted speed to calculations
  • Time.deltaTime = makes your character to move based on time ( even thou you are using fixedUpdate, so that should not matter )

rigidbody2D.AddForce (Vector2.right * speed * Time.deltaTime);

Remember to set some values to drag,friction,gravity and something like that, so physicsEngine actually stops your movement also. If its moving too fast, check the speed variable and playe with masses.

\$\endgroup\$
1
\$\begingroup\$

Consider reading books about realworld physics. "In physics, a force is any interaction which tends to change the motion of an object." - Wikipedia. So... By applying force you make it accelerate and decelerate. You need to have friction or don't use physics at all to make it stop at the end of button press.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.