我正在尝试模拟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 :(得分:0)
if语句逻辑不正确。
double emerge = fluidstart - (currPosy - (objectHeight / 2));
if (emerge <= 0) { // complete submersion
currDepth = objectHeight;
} else {
currDepth = objectHeight - emerge;
}
答案 1 :(得分:0)
问题出在if语句中,这是正确的解决方案:
if (currPosy > (fluidstart + objectHeight/2)){//complete submersion
currDepth = objectHeight;
} else if (currPosy > (fluidstart - objectHeight/2)) {//partial submersion
currDepth = (currPosy + objectHeight/2) - fluidstart;
}