Move a body to the touched position using libgdx and box2d

时光毁灭记忆、已成空白 提交于 2019-12-13 02:08:01

问题


I am trying to move a body with no gravity to the click or touch position and then stop it. However, depending where I click it moves really fast or really slow because of the coordinates of my Vector3. Also, it behaves like that game asteroids which I do not want.

Basically, I just need myBody follows the click of the mouse our touch.

Here where I have got so far:

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {

    camera.unproject(touchPosition.set(screenX, screenY, 0));

    Vector2 velocity = new Vector2(touchPosition.x, touchPosition.y);
    myBody.setLinearVelocity(velocity);

    return true;
}

回答1:


You need to normalize and also take the position of the body itself into account. The following code is untested, but should work.

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    camera.unproject(touchPosition.set(screenX, screenY, 0));

    // calculte the normalized direction from the body to the touch position
    Vector2 direction = new Vector2(touchPosition.x, touchPosition.y);
    direction.sub(myBody.getPosition());
    direction.nor();

    float speed = 10;
    myBody.setLinearVelocity(direction.scl(speed));

    return true;
}


来源:https://stackoverflow.com/questions/23477391/move-a-body-to-the-touched-position-using-libgdx-and-box2d

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!