2015-06-01 41 views
1

我有一個重力運動體0,我想從特定點移動到我的世界座標中的特定點。我試圖將代碼從here 調整爲下面的代碼。但身體保持不動,不動?將身體以恆定速度移動到世界座標中的特定點

@Override 
    public void act(float delta) { 
    super.act(delta); 

    //Target position in world coordinates 
    Vector2 targetPosition = new Vector2(4.5142856f, -4.228572f); 

    //target speed 
    float targetSpeed = 1f; 

    //direction 
    Vector2 direction = targetPosition.sub(body.getPosition()); 

    //distance 
    float distanceToTravel = direction.nor().len2(); 

    // For most of the movement, the target speed is ok 
    float speedToUse = targetSpeed; 

    float distancePerTimestep = speedToUse/60.0f; 
    if (distancePerTimestep > distanceToTravel) 
     speedToUse *= (distanceToTravel/distancePerTimestep); 

    Vector2 desiredVelocity = direction.scl(speedToUse); 
    Vector2 changeInVelocity = desiredVelocity.sub(body.getLinearVelocity()); 

    Vector2 force = new Vector2(changeInVelocity.scl(body.getMass() * 60.0f)); 
    System.out.println(force); 

    body.applyForce(force, body.getWorldCenter(), true); 

} 

回答

2

好吧我想通了。下面的方法將返回正確的速度,以便身體可以達到目標點。

public Vector2 calculateVelocity(Vector2 target) { 
    Vector2 direction = new Vector2(target.x - body.getPosition().x, target.y - body.getPosition().y).nor(); 
    float speed = Constants.enemySpeed; 
    return new Vector2(speed * direction.x, speed * direction.y); 
} 
相關問題