libgdx - Box2d body 如何检查子弹位置是否到达目标位置?

libgdx - How Box2d body check if bullet position has reach target position?

这是下面的link,我如何使用触摸点将子弹移动到目标位置。 (Move a body to the touched position using libgdx and box2d)

我的问题是,如果弹体已经到达目标位置,我该如何停止弹体。

我已经尝试了下面的代码,它工作正常。

PIXEL_TO_METER = 1/32.0f
time step = 1/45.0f, velocity iteration = 6, position iteration = 2
float distanceTravelled = targetDirection.dst(bulletPosition);
if(distanceTravelled >= MAX_DISTANCE){
   // stop
} else {
  // move body
}

但我想将子弹停在目标位置,而不是 MAX_DISTANCE。但是我不知道该怎么做。

您需要检查子弹是否接近您的目标,足以说明它已经到达目标。

    float distance = targetPosition.dst(bulletPosition);
    if(distance <= DEFINED_PRECISION){
        // stop
        // also you can set the target's position to the bullet here
    } else {
        // move body
    }

为什么 near 而不是 exactly 在那个点?子弹以某种定义的速度前进,比如说 10px 每秒 。如果你有 60fps,这意味着在每一帧中,子弹都会移动 10/60px

如果项目符号从位置 0 开始,它的下一个位置(在下一帧中)将为

1/6 (frame 1)
2/6 (frame 2)
3/6 (frame 3)
...

如果目标在1.5/6位置你可以看到虽然在frame 1子弹还没有到达目标在下一帧它已经通过了 就像从未检测到碰撞一样。这就是为什么你需要定义一些精度。它的值应至少为 1 帧步长 ,因此在本例中为 1/6

    float DEFINED_PRECISION = 1/6f;