浮力仿真
问题描述:
我想模拟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();
}
}
答
if语句逻辑不正确。
double emerge = fluidstart - (currPosy - (objectHeight/2));
if (emerge <= 0) { // complete submersion
currDepth = objectHeight;
} else {
currDepth = objectHeight - emerge;
}
答
的问题是在if语句,这是正确的解决方案:
if (currPosy > (fluidstart + objectHeight/2)){//complete submersion
currDepth = objectHeight;
} else if (currPosy > (fluidstart - objectHeight/2)) {//partial submersion
currDepth = (currPosy + objectHeight/2) - fluidstart;
}
您好,感谢您的回答!这实际上是if语句的问题,但解决方案与你的解决方案有点不同,因为这种情况下的y轴向下。 currDepth = 0的情况被覆盖,因为它的值在循环的开始被初始化为该值。 – u09
@ u09编辑。对不起,我错过了那一点 - 我以为你宣布它_way_外像其他变量:) – 2016-05-30 16:30:16