简体   繁体   中英

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);
    }

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM