1

我必须制造一辆静止不动但移动炮塔并发射导弹的坦克。

由于这是我的第一个 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;

}

}

运行游戏的方法 run...

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);
                    }
                }
            }
        }

所以问题是,我如何让子弹在从炮塔到屏幕末端的单次空格键按下时发射?

你能帮帮我吗,我似乎在黑暗中......

谢谢,

尼克萨

4

1 回答 1

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);

有很多调整可以使轨迹更加逼真,但这应该可以帮助您入门。

于 2011-03-23T02:33:17.020 回答