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

标签 java libgdx 2d physics

问题

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

Visual

示例代码

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. 主体位于目标点之前,并且其距离大于DEFINED_PRECISION,因此它正在向前移动
  2. 主体位于目标点之后,并且其距离大于DEFINED_PRECISION,因此它向后移动
  3. 主体位于目标点之前,并且其距离大于DEFINED_PRECISION...

这就是它摇晃的原因:)

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

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

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

关于java - libgdx box2d body - 为什么到达接触点位置后 body 会摇晃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38239532/

相关文章:

java - libGDX - 对不同的屏幕使用不同的 InputProcessors?

java - 如何通过 java httpClient 查找目标 Web 服务器的任何信息?

java - MapStruct:如何使用可选参数执行@AfterMapping?

java - 多种平台上的 LibGDX 开发

ios - 触摸移动SKSpriteNode,半屏点加速

animation - Unity - 在运行时改变游戏对象形状的最佳方式

java - 检查 if 语句中所有条件的最有效方法?

java - 在 Libgdx/Scene2D SelectBox 中显示图像

java - 玩家角色移动错误 LibGDX RPG

c++ - OpenGL reshape 函数