我必须制造一个静止的坦克,但移动他的炮塔射击导弹。
由于这是我有史以来的第一个Android应用程序,我也没有进行任何游戏开发,我遇到了一些问题......
现在,一旦我阅读了LunarLander示例代码的Android教程,我就完成了坦克和移动炮塔。所以这段代码基于LunarLander代码。
但是我在导弹射击时遇到了麻烦,然后按下SPACE按钮。
private void doDraw(Canvas canvas) {
canvas.drawBitmap(backgroundImage, 0, 0, null);
// draws the tank
canvas.drawBitmap(tank, x_tank, y_tank, new Paint());
// draws and rotates the tank turret
canvas.rotate((float) mHeading, (float) x_turret + mTurretWidth, y_turret);
canvas.drawBitmap(turret, x_turret, y_turret, new Paint());
// draws the grenade that is a regular circle from ShapeDrawable class
bullet.setBounds(x_bullet, y_bullet, x_bullet + width, y_bullet + height);
bullet.draw(canvas);
}
更新游戏方法
private void updateGame() throws InterruptedException {
long now = System.currentTimeMillis();
if (mLastTime > now)
return;
double elapsed = (now - mLastTime) / 1000.0;
mLastTime = now;
// dUP and dDown, rotates the turret from 0 to 75 degrees.
if (dUp)
mHeading += 1 * (PHYS_SLEW_SEC * elapsed);
if (mHeading >= 75) mHeading = 75;
if (dDown)
mHeading += (-1) * (PHYS_SLEW_SEC * elapsed);
if (mHeading < 0) mHeading = 0;
if (dSpace){
// missile Logic, a straight trajectorie for now
x_bullet -= 1;
y_bullet -= 1;
}
}
运行游戏的方法运行...
public void run() {
while (mRun) {
Canvas c = null;
try {
c = mSurfaceHolder.lockCanvas(null);
synchronized (mSurfaceHolder) {
if (mMode == STATE_RUNNING)
updateGame();
doDraw(c);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null) {
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
所以问题是,如何在从炮塔到屏幕末端的单个SPACE按键上发射子弹?
你能帮帮我吗,我好像在这里黑暗......
谢谢,
Niksa
答案 0 :(得分:0)
从评论中听起来你的问题是你希望子弹在抛物线中移动看起来更逼真。您拥有distance = time * velocity
的解决方案的一半,但您还需要velocity = time * acceleration
。您希望在每次更新中都这样:
x_bullet += elapsed * vx_bullet;
y_bullet += elapsed * vy_bullet;
vx_bullet += elapsed * ax_bullet; // ax_bullet = 0 unless you want simple wind resistance
vy_bullet += elapsed * ay_bullet; // ay_bullet = gravity
您的重力常数取决于图形比例。现实生活中它的速度为9.8 m / s ^ 2,但您必须根据每米的像素进行调整。速度矢量将根据水箱的初速度进行初始化。如果初速度存储在muzzle_vel
中,并且炮塔与正x轴的角度为theta
,那么你将拥有
vx_bullet = muzzle_vel * Math.cos(theta);
vy_bullet = muzzle_vel * Math.sin(theta);
有很多调整可以使轨迹更加逼真,但这应该可以让你开始。