我制作了一个 body ,当单击按钮时我想要移动该 body ,我已经能够使用 body.setLinearVelocity()
移动 body ,但它不准确。假设我想以 40 的 X 线速度将 body 移动 7 米,我该怎么做?
//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()
,但我需要 body 实际移动而不是传送。预先感谢您
最佳答案
我不知道你的代码示例有多完整,但从我在这里看到的来看,你至少错过了 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)
如何处理此问题的一些(未经测试的)想法:
关于java - Libgdx Box2d body 沿线性方向移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48733343/