0

我在Andengine中有box2d身体。我想一次将这个身体从(0,0)移动到(100,100)(恒定速度)。这怎么可能?我试过这个代码: this.body.setLinearVelocity(new Vector2(1, 0)); 但它在不停地移动。

4

1 回答 1

0

我想沿着预定义路径移动的最简单方法是使用Body.setTransform(...). 这样我们基本上忽略了所有的力、摩擦力、扭矩、碰撞等,直接设置身体的位置。

我不知道Andengine,所以这只是伪代码:

public void updateGameLoop(float deltaTime) {
    Vector2 current = body.getPosition();
    Vector2 target = new Vector2(100, 100);

    if (!current.equals(target)) {
        float speed = 20f;
        Vector2 direction = target.sub(current);
        float distanceToTarget = direction.len();
        float travelDistance = speed * deltaTime;

        // the target is very close, so we set the position to the target directly
        if (distanceToTarget <= travelDistance) {
            body.setTransform(target, body.getAngle());
        } else {
            direction.nor();
            // move a bit in the target direction 
            body.setTransform(current.add(direction.mul(travelDistance)), body.getAngle());
        }
    }
}
于 2013-10-20T18:32:08.227 回答