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 }
Note
You will need to import the RectF
class.
import android.graphics.RectF;
In the previous code this line returns true when the ball hits the bat and will cause the code inside to execute.
if(RectF.intersects(mBat.getRect...