21.10.2016 Views

android-6-for-programmers-3rd

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

6.11 Cannon Class 233<br />

38 // creates and fires Cannonball in the direction Cannon points<br />

39 public void fireCannonball() {<br />

40 // calculate the Cannonball velocity's x component<br />

41 int velocityX = (int) (CannonView.CANNONBALL_SPEED_PERCENT *<br />

42 view.getScreenWidth() * Math.sin(barrelAngle));<br />

43<br />

44 // calculate the Cannonball velocity's y component<br />

45 int velocityY = (int) (CannonView.CANNONBALL_SPEED_PERCENT *<br />

46 view.getScreenWidth() * -Math.cos(barrelAngle));<br />

47<br />

48 // calculate the Cannonball's radius<br />

49 int radius = (int) (view.getScreenHeight() *<br />

50 CannonView.CANNONBALL_RADIUS_PERCENT);<br />

51<br />

52 // construct Cannonball and position it in the Cannon<br />

53 cannonball = new Cannonball(view, Color.BLACK,<br />

54 CannonView.CANNON_SOUND_ID, -radius,<br />

55 view.getScreenHeight() / 2 - radius, radius, velocityX,<br />

56 velocityY);<br />

57<br />

58 cannonball.playSound(); // play fire Cannonball sound<br />

59 }<br />

60<br />

Fig. 6.12 | Cannon method fireCannonball.<br />

6.11.4 Method draw<br />

The draw method (Fig. 6.13) draws the Cannon on the screen. We draw the Cannon in two<br />

parts. First we draw the Cannon’s barrel, then the Cannon’s base.<br />

61 // draws the Cannon on the Canvas<br />

62 public void draw(Canvas canvas) {<br />

63 // draw cannon barrel<br />

64 canvas.drawLine(0, view.getScreenHeight() / 2, barrelEnd.x,<br />

65 barrelEnd.y, paint);<br />

66<br />

67 // draw cannon base<br />

68 canvas.drawCircle(0, (int) view.getScreenHeight() / 2,<br />

69 (int) baseRadius, paint);<br />

70 }<br />

71<br />

Fig. 6.13 | Cannon method draw.<br />

Drawing the Cannon Barrel with Canvas Method drawLine<br />

We use Canvas’s drawLine method to display the Cannon barrel (lines 64–65). This method<br />

receives five parameters—the first four represent the x-y coordinates of the line’s start<br />

and end, and the last is the Paint object specifying the line’s characteristics, such as its<br />

thickness. Recall that paint was configured to draw the barrel with the thickness given in<br />

the constructor (Fig. 6.10, line 25).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!