Explaining the takeShot method

First up we have the new signature. The method receives two float variables named touchX and touchY. This is just what we need because the onTouchEvent method calls takeShot passing in the float screen coordinates of the player's shot.

void takeShot(float touchX, float touchY){

This next code prints a debugging message to the logcat window and then increments the shotsTaken member variable by one. The next time draw is called (possibly at the end of this method if not a hit) the player's HUD will be updated accordingly.

Log.d("Debugging", "In takeShot");

// Add one to the shotsTaken variable
shotsTaken ++;

Moving on, this code converts the float coordinates in touchX and touchY into an integer grid position by dividing the coordinates by blockSize and casting the answer to int. Note that the values are then stored in horizontalTouched and verticalTouched.

// Convert the float screen coordinates
// into int grid coordinates
horizontalTouched = (int)touchX / blockSize;
verticalTouched = (int)touchY / blockSize;

The next line of code in the takeShot method assigns either true or false to the hit variable. Using logical && we see whether both of horizontalTouched and verticalTouched are the same as subHorizontalPosition and subVerticalPosition, respectively. We can now use hit later in the method to decide whether to call boom or draw.

// Did the shot hit the sub?
hit = horizontalTouched == subHorizontalPosition
      && verticalTouched == subVerticalPosition;

In case the player missed (and usually they will) we calculate the distance of the shot from the sub'. The first part of the code shown next gets the horizontal and vertical distances of the shot from the Sub'. The final line of code uses the Math.sqrt method to calculate the length of the missing side of an imaginary triangle made from the sum of the square of the two known sides. This is Pythagoras's theorem.

// How far away horizontally and vertically
// was the shot from the sub
int horizontalGap = (int)horizontalTouched -
      subHorizontalPosition;
int verticalGap = (int)verticalTouched -
      subVerticalPosition;

// Use Pythagoras's theorem to get the
// distance travelled in a straight line
distanceFromSub = (int)Math.sqrt(
      ((horizontalGap * horizontalGap) +
      (verticalGap * verticalGap)));

Note

If the Math.sqrt looks a bit odd as did the Random.nextInt method, then all will be explained in the next chapter. For now, all we need to know is that Math.sqrt returns the square root of the value passed in as an argument.

Finally, for the takeShot method, we call boom if there was a hit or draw if it was a miss.

// If there is a hit call boom
if(hit) 
   boom();
// Otherwise call draw as usual
else draw();

Let's draw the "BOOM" screen.