- Learning Java by Building Android Games
- John Horton
- 207字
- 2021-07-23 19:02:28
Coding the takeShot method
Let's redo the entire takeShot
method because the signature is changing too. Adapt the takeShot
method to look like this and then we will analyze the code.
Tip
It is probably best to delete it and start again
/* The code here will execute when the player taps the screen It will calculate the distance from the sub' and determine a hit or miss */ void takeShot(float touchX, float touchY){ Log.d("Debugging", "In takeShot"); // Add one to the shotsTaken variable shotsTaken ++; // Convert the float screen coordinates // into int grid coordinates horizontalTouched = (int)touchX/ blockSize; verticalTouched = (int)touchY/ blockSize; // Did the shot hit the sub? hit = horizontalTouched == subHorizontalPosition && verticalTouched == subVerticalPosition; // 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))); // If there is a hit call boom if(hit) boom(); // Otherwise call draw as usual else draw(); }
The takeShot
method is quite long so let's give explaining the code a whole new section of its own.