// The SurfaceView class implements onTouchListener // So we can override this method and detect screen touches. @Override public boolean onTouchEvent(MotionEvent motionEvent) { switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) { // Player has touched the screen case MotionEvent.ACTION_DOWN: paused = false; if (motionEvent.getY() > screenY - screenY / 8) { if (motionEvent.getX() > screenX / 2) { playerShip.setMovementState(playerShip.RIGHT); if (playerShip.getX() <= 1116.6749) { canvas.drawBitmap(playerShip.getBitmap(), playerShip.getX(), screenY - 110, paint); } } else { playerShip.setMovementState(playerShip.LEFT); // if (playerShip.getX() < -26.160135){ // playerShip.setMovementState(playerShip.RIGHT); // } } } if (motionEvent.getY() < screenY - screenY / 8) { // Shots fired if (bullet.shoot(playerShip.getX() + playerShip.getLength() / 2, screenY, bullet.UP)) { soundPool.play(shootID, 1, 1, 0, 0, 1); } } break; // Player has removed finger from screen case MotionEvent.ACTION_UP: if (motionEvent.getY() > screenY - screenY / 10) { playerShip.setMovementState(playerShip.STOPPED); } break; } return true; }
private void draw() { // Make sure our drawing surface is valid or we crash if (ourHolder.getSurface().isValid()) { // Lock the canvas ready to draw canvas = ourHolder.lockCanvas(); // Draw the background color canvas.drawColor(Color.argb(255, 26, 128, 182)); // Resources res = getResources(); // Bitmap bitmap = BitmapFactory.decodeResource(res, R.drawable.background); // canvas.drawBitmap(bitmap, 0, 0, paint); // Choose the brush color for drawing paint.setColor(Color.argb(255, 255, 255, 255)); // Now draw the player spaceship canvas.drawBitmap(playerShip.getBitmap(), playerShip.getX(), screenY - 110, paint); // Draw the invaders for (int i = 0; i < numInvaders; i++) { if (invaders[i].getVisibility()) { if (uhOrOh) { canvas.drawBitmap( invaders[i].getBitmap(), invaders[i].getX(), invaders[i].getY(), paint); } else { canvas.drawBitmap( invaders[i].getBitmap2(), invaders[i].getX(), invaders[i].getY(), paint); } } } // Draw the bricks if visible for (int i = 0; i < numBricks; i++) { if (bricks[i].getVisibility()) { canvas.drawRect(bricks[i].getRect(), paint); } } // Draw the players bullet if active if (bullet.getStatus()) { canvas.drawRect(bullet.getRect(), paint); } // Draw the invaders bullets // Update all the invader's bullets if active for (int i = 0; i < invadersBullets.length; i++) { if (invadersBullets[i].getStatus()) { canvas.drawRect(invadersBullets[i].getRect(), paint); } } // Draw the score and remaining lives // Change the brush color paint.setColor(Color.argb(255, 249, 129, 0)); paint.setTextSize(40); canvas.drawText("Score: " + score + " Lives: " + lives, 10, 50, paint); // Draw everything to the screen ourHolder.unlockCanvasAndPost(canvas); } }