gustavo302
gustavo302

Reputation: 79

How to use addforce on a 2d object to move it

I need to move a 2d ball around using the arrows keys right and left. However when i click the right one the ball sometimes goes to the left and so on... And yes, i'm using Rigibody2D to do this.

 if (Input.GetKeyDown("right"))
    {
        bola.AddForce(transform.right * velocity,ForceMode2D.Force);
    }

    if (Input.GetKeyDown("left"))
    {
        bola.AddForce(-transform.right * velocity,ForceMode2D.Force);
    }

Upvotes: 0

Views: 1032

Answers (1)

Jack10689
Jack10689

Reputation: 181

Maybe your balls are rotating because of the force you apply and hence you use local right, the direction changes with the rotation. You should try to deactivate rigidbody rotation, or use global directions.

if (Input.GetKeyDown("right"))
{
    bola.AddForce(Vector2.right * velocity,ForceMode2D.Force);
}

if (Input.GetKeyDown("left"))
{
    bola.AddForce(-Vector2.right * velocity,ForceMode2D.Force);
}

Upvotes: 2

Related Questions