Coding the collision detection and playing sounds
Now we have done so much theory and preparation we can finish everything off very quickly. We will write code to detect all the various collisions, using the RectF
intersects method and play sounds and call the required methods of our classes.
The bat and the ball
Add the following highlighted code inside the detectCollisions
method.
private void detectCollisions(){ // Has the bat hit the ball? if(RectF.intersects(mBat.getRect(), mBall.getRect())) { // Realistic-ish bounce mBall.batBounce(mBat.getRect()); mBall.increaseVelocity(); mScore++; mSP.play(mBeepID, 1, 1, 0, 0, 1); } // Has the ball hit the edge of the screen // Bottom // Top // Left // Right }
Tip
You will need to import the RectF
class.
Get Learning Java by Building Android Games - Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.