2015-02-06 121 views
1

我的遊戲場景由四面牆體組成,它們是靜態物體,以及一個平臺板,它是運動型的,只能水平滑動,如下圖所示。基於加速度傳感器如何禁止運動物理體通過靜態物體?

enter image description here

平臺身體動作,看到這個代碼

@Override 
public void onAccelerationChanged(AccelerationData pAccelerationData) { 
    mPlatformBody.setLinearVelocity(pAccelerationData.getX() * 10, 0); 
} 

我的問題是當平臺熄滅的邊界牆,它不應該。爲了解決這個問題,一旦它試圖突破界限,我已經將其速度設置爲零。看到這個代碼

Rectangle rect = new Rectangle(camWidth/2 - 40, camHeight/2 - 5, 
     80, 10, mEngine.getVertexBufferObjectManager()) { 
    @Override 
    protected void onManagedUpdate(float pSecondsElapsed) { 

     if (this.getX() <= 1) { 
      mPlatformBody.setLinearVelocity(0, 0); 
     } 

     if ((this.getX() + 80 >= camWidth - 1)) { 
      mPlatformBody.setLinearVelocity(0, 0); 
     } 

     super.onManagedUpdate(pSecondsElapsed); 
    } 
}; 

通過上面的代碼,仍然這個平臺可以熄滅屏幕。

任何人都可以請幫助我,我該如何克服這個問題?

+0

你也有它的位置重置到它以前還是隻牆的邊界之外,否則會獲得一些速度,動一動,你重置速度爲0,依此類推。它會很慢,但它仍然會移動。 – LearnCocos2D 2015-02-06 16:14:16

+0

@ LearnCocos2D我如何重置它的位置?據我所知box2d沒有提供任何手動定位主體的方法 – 2015-02-06 16:17:29

+0

您可以使用b2Body的SetTransform函數來設置主體的位置。 – iforce2d 2015-02-07 06:38:28

回答

0

正如@ LearnCocos2D所述,我應該在試圖離開屏幕時將平臺主體重置爲合法位置。爲此,我應該使用setTransform方法Body類(如@iforce2d所說)。

對於處理setTransform,有兩點重要。

  • AndEngine使用左上角作爲精靈的錨,但Box2D中使用中心爲主體的錨。
  • Box2d使用儀表作爲其單位,所以我們必須將所有像素單位轉換爲儀表單位。

示例:假設我們要身體移動到(3,4)點(像素)。

float x = 3; // in pixels (AndEngine unit) 
    float y = 4; // in pixels (AndEngine unit) 
    float wD2 = sprite.getWidth()/2; 
    float hD2 = sprite.getHeight()/2; 
    float angle = body.getAngle(); // preserve original angle 

    body.setTransform((x + wD2)/PIXEL_TO_METER_RATIO_DEFAULT, 
         (y + hD2)/PIXEL_TO_METER_RATIO_DEFAULT, 
         angle); 

注意PIXEL_TO_METER_RATIO_DEFAULT爲32