【发布时间】:2016-05-29 18:14:29
【问题描述】:
我正在尝试在 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();
}
}
【问题讨论】:
标签: android 2d game-physics