2016-05-29 141 views
0

我想模擬Android應用程序的2D對象上的浮力行爲,不存在摩擦。有些東西不能正常工作:「反彈」的高度以不規則的方式變化,我認爲錯誤應該在速度的更新中,但我不確定。浮力仿真

任何人都可以在我的代碼中看到錯誤嗎?

public class MainActivity extends Activity { 

    Semaphore moveSemaphore = new Semaphore(1); 
    static WindowManager.LayoutParams params; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     params = new WindowManager.LayoutParams(80, 80, 
       WindowManager.LayoutParams.TYPE_APPLICATION, 
       WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, 
       PixelFormat.TRANSPARENT); 

     final BallView ball = new BallView(this); 
     addContentView(ball, params); 
     ball.setX(100); 
     ball.setY(50); 

     final Thread move = new Thread(new Runnable(){ 
      double speed = 0; 
      double G = 9; 
      double fullBuoyancy = -G * 10; 
      double prevtime = System.currentTimeMillis(); 
      double elapsed; 

      double fluidstart = 300; 
      double objectHeight = 100; 
      double currPosy = 50; 
      double p; 

      @Override 
      public void run() { 

       while(true){ 

        try { 
         moveSemaphore.acquire(); 
        } catch (InterruptedException e) { 
         e.printStackTrace(); 
        } 

        runOnUiThread(new Runnable() { 
         @Override 
         public void run() { 
          double currDepth = 0; 
          long currtime = System.currentTimeMillis(); 
          elapsed = (currtime - prevtime) * 0.01; 
          prevtime = currtime; 
          currPosy = ball.getY(); 

          // COMPUTE HOW MUCH OF THE BALL IS INSIDE OF THE FLUID 
          if (currPosy > (fluidstart + objectHeight/2)){ 
           currDepth = objectHeight; 
          } else if (currPosy > (fluidstart - objectHeight/2)) { 
           currDepth = currPosy - fluidstart; 
          } 


          p = currDepth/objectHeight; // PERCENTAGE OF THE FULL BUOYANT FORCE TO BE APPLIED 
          speed = speed + (G + fullBuoyancy * p) * elapsed; 

          currPosy += speed * elapsed; 
          ball.setY((float)currPosy); 

          moveSemaphore.release(); 
         } 
        }); 
       } 
      } 
     }); 

     move.start(); 
    } 
} 

回答

0

if語句邏輯不正確。

double emerge = fluidstart - (currPosy - (objectHeight/2)); 
if (emerge <= 0) { // complete submersion 
    currDepth = objectHeight; 
} else { 
    currDepth = objectHeight - emerge; 
} 
+0

您好,感謝您的回答!這實際上是if語句的問題,但解決方案與你的解決方案有點不同,因爲這種情況下的y軸向下。 currDepth = 0的情況被覆蓋,因爲它的值在循環的開始被初始化爲該值。 – u09

+0

@ u09編輯。對不起,我錯過了那一點 - 我以爲你宣佈它_way_外像其他變量:) – 2016-05-30 16:30:16

0

的問題是在if語句,這是正確的解決方案:

if (currPosy > (fluidstart + objectHeight/2)){//complete submersion 
    currDepth = objectHeight; 
} else if (currPosy > (fluidstart - objectHeight/2)) {//partial submersion 
    currDepth = (currPosy + objectHeight/2) - fluidstart; 
}