问题
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());
在你的循环中)并检查它是否更大。
当时的情况是这样
- 主体位于目标点之前,并且其
距离
大于DEFINED_PRECISION
,因此它正在向前移动 - 主体位于目标点之后,并且其
距离
大于DEFINED_PRECISION
,因此它向后移动 - 主体位于目标点之前,并且其
距离
大于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/