Detect collision between two Sprites
To detect collision between two Sprites among many of the existing, we have to maintain a list of all the sprites that are drawn on the Canvas, and in every update (of all Sprites) to the Canvas, we have to run a loop among the available Sprites, if there is an overlap.
In our previous Android Game Development tutorial, we have gone to the extent of making the sprites move and responding the sprites to the user input (touch). In this tutorial, we shall learn how to detect collision between the two Sprites, Grenade and Player. This tutorial is built on the previous tutorial, so you may have a look at it.
Following is a step by step guide.
Step 1: Get Rectangles from your Sprites.
val grenadeRect: Rect = Rect(grenade.x, grenade.y, grenade.x+grenade.w, grenade.y+grenade.h)
val playerRect: Rect = Rect(player.x, player.y, player.x+player.w, player.y+player.h)
Step 2: Check for Intersection.
val grenadeRect: Rect = Rect(grenade.x, grenade.y, grenade.x+grenade.w, grenade.y+grenade.h)
val playerRect: Rect = Rect(player.x, player.y, player.x+player.w, player.y+player.h)
if(grenadeRect.intersect(playerRect)){
collided=true
System.out.println("Collided.")
}
Step 3: Update the Sprites based on the “collided” status.
Conclusion
In this Kotlin Android Tutorial, we have learnt to detect collision between two sprites.