Libgdx Box2d Body在线性方向移动?

时间:2018-02-11 15:51:15

标签: java libgdx box2d

当我点击一个按钮时,我想要移动一个身体,我已经能够使用body.setLinearVelocity()移动身体,但它不准确。让我们说我想让我的身体移动七米,线性X速度为40,我该怎么做?

//BODY MOVEMENT
//timer = I try to move the body for a certain amount of time
/*isMoveRight and isMoveLeft are Just booleans for activating and deactivating movement*/
        if(Gdx.input.isKeyJustPressed(Input.Keys.RIGHT)){
            timer = 0f;
            isMoveRight = true;
            isMoveLeft = false;
        }else if(Gdx.input.isKeyJustPressed(Input.Keys.LEFT)){
            timer = 0f;
            isMoveLeft = true;
            isMoveRight = false;
        }

        if(isMoveRight == true && timer < 0.1f){
            timer += 1f * delta;   //activate timer
            body.setLinearVelocity(52f, 0f);
        }else if(isMoveLeft == true && timer < 0.1f){
            timer += 1 * delta;
            body.setLinearVelocity(-52f, 0f);
        }

我可以使用body.setTransform()但我需要身体实际移动而不是传送。提前谢谢

1 个答案:

答案 0 :(得分:2)

我不知道您的代码示例有多完整,但从我看到的情况来看,您至少错过了0.1秒后将速度重置为0的部分。

else {
    body.setLinearVelocity(0F, 0F);
}

除此之外,您的方法在移动距离上略有模糊,因为根据您的帧率,您的支票timer < 0.1f不是很准确:

timer = 0.099 -> distance = 5.148
timer = 0.132 -> distance = 6.881 (one frame later with 30 frames/second)

一些(未经测试的)想法如何处理这个问题:

  1. 使用RopeJoint强制身体和起点之间的最大距离(在这种情况下也必须是身体)
  2. 测量距离(使用Vector2类)并根据需要将其传送回最大距离处。 (无论如何,你应该使用距离而不是计时器)
  3. 如果它靠近目标,你的身体会慢下来,这至少有助于减少错误