Method alignCannon
(Fig. 6.14) aims the cannon at the point where the user touched the screen. Line 335 gets the x- and y-coordinates of the touch from the MotionEvent
argument. We compute the vertical distance of the touch from the center of the screen. If this is not zero, we calculate cannon barrel’s angle
from the horizontal (line 345). If the touch is on the lower-half of the screen we adjust the angle
by Math.PI
(line 349). We then use the cannonLength
and the angle
to determine the x- and y-coordinate values for the endpoint of the cannon’s barrel—this is used to draw a line from the cannon base’s center at the left edge of the screen to the cannon’s barrel endpoint.
331 // aligns the cannon in response to a user touch
332 public double alignCannon(MotionEvent event)
333 {
334 // get the location of the touch in this view
335 Point touchPoint = new Point((int) event.getX(), (int) event.getY());
336
337 // compute the touch's distance from center of the screen
338 // on the y-axis
339 double centerMinusY = (screenHeight / 2 - touchPoint.y);
340
341 double angle = 0; // initialize angle to 0
342
343 // calculate the angle the barrel makes with the horizontal
344 if (centerMinusY != 0) // prevent division by 0
345 angle = Math.atan((double) touchPoint.x / centerMinusY);
346
347 // if the touch is on the lower half of the screen
348 if (touchPoint.y > screenHeight / 2)
349 angle += Math.PI; // adjust the angle
350
351 // calculate the endpoint of the cannon barrel
352 barrelEnd.x = (int) (cannonLength * Math.sin(angle));
353 barrelEnd.y =
354 (int) (-cannonLength * Math.cos(angle) + screenHeight / 2);
355
356 return angle; // return the computed angle
357 } // end method alignCannon
358