2012-09-25 35 views
1

在AndEngine遊戲中,我想拋出一個球物理體。用戶設置其角度並強制拋出它。它的情況與我們在「憤怒的小鳥」中看到的情況相同。我已經計算了力和角度,但是我很困惑如何同時應用兩個球,這意味着球應該以計算出的角度投擲,但是需要特別的力量。任何人都可以引導我走向正確的方向嗎?andengine用力和特定角度拋球

這裏是我的代碼片段:

@Override 
public boolean onAreaTouched(TouchEvent event,ITouchArea pTouchArea, float x, float y) { 
    // TODO Auto-generated method stub 
    if(event.isActionDown()) { 
     ...... 
    } 
    else if(event.isActionMove()) { 
     ...... 
    } 
    else if(event.isActionCancel() || event.isActionOutside() || event.isActionUp()) { 
     ..... 
     launchHero(hero, string1.getX1()/PIXEL_TO_METER_RATIO_DEFAULT, string1.getY1()/PIXEL_TO_METER_RATIO_DEFAULT, x/PIXEL_TO_METER_RATIO_DEFAULT, y/PIXEL_TO_METER_RATIO_DEFAULT); 
} 

public void launchHero(Hero hero, float originX, float originY, float fingerX, float fingerY) { 
    Vector2 shoot = new Vector2((originX - fingerX), -(originY - fingerY)); 
    shoot = shoot.nor().mul(10); 

    hero.getBody().setLinearVelocity(shoot); 

} 
    } 

    return false; 

} 

我已經加入負(originY - fingerY),因爲如果我不這樣做,球先下降再與基地相撞後,其上升。

回答

4

這很簡單,使用Body.setLinearVelocity(Vector2 pVector)。方向和力都由向量的參數決定。下面是一個示例代碼:

Vector2 shoot = new Vector2((originX - fingerX), (originY - fingerY)); 
body.setLinearVelocity(shoot); 

這將拍攝體,用手指和產地,或在憤怒的小鳥,手指和吊帶的情況下進行的方向。

如果你想使力常數,並通過一些數字相乘,就可以開拍之前做到這一點:

shoot = shoot.nor().mul(multiplier); 
+0

我試過這個。但即使用戶希望它向下移動,球也會向上移動。 –

+0

請給我一個樣本,說明你給originX,originY,fingerX,fingerY提供了什麼值。我使用這個代碼,它適用於我。 – JohnEye

+0

originX = 4.78125,originY = 9.4375,fingerX = 0.625,fingerY = 0.625 –

0

您可以使用

body.applyLinearImpulse(Vector2 impulse, Vector2 point) 

我更喜歡setLinearVelocity此功能,因爲它給了更多的可能性。要使用此功能,您需要在座標和身體的適用位置給予衝動。