0

我想在按下向上按钮时移动播放器图像。我尝试了 onClick() 方法,但它不起作用。当按下向上按钮时,播放器应该向上移动一些像素。我尝试了类似 getButtonState 之类的东西,我在 Android 开发者页面上看到过,但我不明白它是如何工作的……有什么建议吗?

private Context mContext;
int enemy_x = -1;
int enemy_y = -1;
int player_x = -1;
int player_y = -1;

private int enemy_xVelocity = 15;
private int enemy_yVelocity = 0;
private int player_xVelocity = 0;
private int player_yVelocity = 10;
private Handler h;
private final int FRAME_RATE = 60;

Button upbutton = (Button) findViewById(R.id.upbutton);

public AnimatedView(Context context, AttributeSet attrs) {
    super(context, attrs);
    mContext = context;
    h = new Handler();
}

private Runnable r = new Runnable() {
    @Override
    public void run() {
        invalidate();
    }
};

protected void onDraw(Canvas c) {
    BitmapDrawable enemy = (BitmapDrawable) mContext.getResources()
            .getDrawable(R.drawable.enemy);
    BitmapDrawable player = (BitmapDrawable) mContext.getResources()
            .getDrawable(R.drawable.player);

    // enemy movement
    if (enemy_x < 0 && enemy_y < 0) {
        enemy_x = this.getWidth() / 2;
        enemy_y = this.getHeight() / 2;
    } else {
        enemy_x += enemy_xVelocity;
        enemy_y += enemy_yVelocity;
        if ((enemy_x > this.getWidth() - enemy.getBitmap().getWidth())
                || (enemy_x < 0)) {
            enemy_xVelocity = enemy_xVelocity * -1;
        }
        if ((enemy_y > this.getHeight() - enemy.getBitmap().getHeight())
                || (enemy_y < 0)) {
            enemy_yVelocity = enemy_yVelocity * -1;
        }
    }

    // player movement

    if (player_x < 0 && player_y < 0) {
        player_x = (this.getWidth() / 2) - 20;
        player_y = this.getHeight() - 150;
    } else {


        player_x += player_xVelocity;
        player_y += player_yVelocity;
        if ((player_x > this.getWidth() - player.getBitmap().getWidth())
                || (player_x < 0)) {
            player_xVelocity = player_xVelocity * -1;
        }
        if ((player_y > this.getHeight() - player.getBitmap().getHeight())
                || (player_y < 0)) {
            player_yVelocity = 0;
        }

    }

    c.drawBitmap(enemy.getBitmap(), enemy_x, enemy_y, null);
    c.drawBitmap(player.getBitmap(), player_x, player_y, null);
    h.postDelayed(r, FRAME_RATE);
}
4

0 回答 0