libgdx box2d body - 为什么 body 到达接触点位置后会晃动?

libgdx box2d body - Why the body is shaking after reaching the touchpoint position?

问题

If the bullet reaches its destination the body is shaking, back and fort from destination to previous position then back again to destination and so on.. and so fort... Strange behavior

示例代码

Vector2 targetPosition =
// Copied target position and subtracted by bullet position
Vector2 targetDirection = targetPosition.cpy().sub(bulletPosition);

float distance = bulletPosition.dst(targetPosition);

float speed = 16;
Vector2 velocity = targetDirection
        .cpy() // Copied target direction
        .nor() // normalize to avoid getting the direction as speed
        .scl(speed);  // scaled by speed
// the distance is not accurate, so we get the time step as defined precision
float DEFINED_PRECISION = Constants.TIME_STEP;
// check if the bullet is near or maybe match the touch point
if(distance >= DEFINED_PRECISION) {
   // move the bullet
   body.setLinearVelocity(velocity);
} else {
   // stop the bullet
   body.setLinearVelocity(0,0);
}

可能你的 DEFINED_PRECISION 太低了 - 你应该在每一步注销 body's 位置(即使在你的循环中添加类似 System.out.println(body.getPosition()); 的东西)并检查它是否更大.

当时的情况是

  1. Body在目标点之前并且distanceDEFINED_PRECISION大所以它被向前移动
  2. Body 在目标点之后,它的 distanceDEFINED_PRECISION 大,所以它正在向后移动
  3. Body 在目标点之前并且 distance 大于 DEFINED_PRECISION...

这就是它颤抖的原因:)

首先,您应该更改 DEFINED_PRECISION - 检查 在一帧中移动了多少 body 并将此值除以 2 应该是 DEFINED_PRECISION (因为 body 和两帧之间的目标之间有最大距离)。另外我猜比将 velocity 设置为 (0,0) 更好的方法是将目标的位置直接设置为 body

    else {
        body.setTransform(target.getPosition().x, target.getPosition().y, body.getAngle());
    }

当然,如果你的步幅不是很大——那么变化将是不可见的,最终位置将恰好是目标的位置