使用libgdx和box2d将主体移动到触摸位置

Dev*_*ter 1 box2d libgdx

我试图将没有重力的身体移动到点击或触摸位置然后停止它.但是,根据我点击的位置,由于我的Vector3的坐标,它移动速度非常快或非常慢.此外,它的行为就像我不想要的游戏小行星.

基本上,我只需要myBody按下鼠标点击我们的触摸.

到目前为止我在这里:

@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;
}
Run Code Online (Sandbox Code Playgroud)

noo*_*one 6

您需要规范化并考虑身体本身的位置.以下代码未经测试,但应该可以使用.

@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;
}
Run Code Online (Sandbox Code Playgroud)