2016-07-07 64 views
2

问题libgdx box2d body - 为什么身体在到达接触点位置后发抖?

如果子弹到达目的地的身体颤抖,背部和堡垒从目的地到以前的位置,然后再次回到 目的地等..等等堡... 奇怪的行为

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); 
} 

回答

2

可能是你DEFINED_PRECISION太低 - 你应该(甚至通过添加类似System.out.println(body.getPosition());你的循环内)注销body's位置在每一个步骤,检查wheter这是更大的。

的情况是那么

  1. 身体是目标点之前,它的distance是大于DEFINED_PRECISION所以它向前移动,
  2. 身体是目标点后,它的distance是大于DEFINED_PRECISION所以它正在移动落后
  3. 身体在目标点之前,它的distance大于DEFINED_PRECISION ...

这就是为什么它是浑身发抖的:)

首先,你应该改变你的DEFINED_PRECISION - 检查多少身体被移动在一帧这个值由2划分应该是DEFINED_PRECISION(因为两帧之间存在身体与目标之间的最大距离)。此外,我想这比设置velocity(0,0)将目标的位置直接设置成体

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

课的情况下,当你的脚步是不是非常大的 - 那么,变化将是无形的和最后的位置将是确切的目标位置