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



我正试图将一个没有重力的物体移动到点击或触摸位置,然后停止它。然而,根据我点击的位置,它移动得非常快或非常慢,因为我的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;
}

您需要规范化并考虑正文本身的位置。下面的代码没有经过测试,但是应该可以工作。

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

最新更新