The codeleap for this section may be accessed here. In this section, we will discuss methods we may use in order to detect collisions. Following this explanation, we will implement them using intersect()
and within()
.
Subsections
01 A Word on Collisions
02 Using Intersect
03 Using Within
Collision detection is used to check when sprites are intersecting with other sprites. Some examples of implemented collision detection include: a punch colliding with an opponent, a projectile hitting the player, and an NPC bouncing off of a table. Collision detection done well can really make a game shine.
One method enchant.js provides is the intersect method. This method allows us to check when a sprite is intersecting with another sprite. It takes in a reference to another sprite as a parameter, and returns true when the two are intersecting. The bounding box of each sprite is defined by the sprite’s height and width.
i.e) intersect(SOME_SPRITE) to return true when sprite intersects with SOME_SPRITE
Let’s implement Collision Detection in our example code. (Once again, you can access it from here.)
onenterframe
function under 06.2 Intersect:
if(this.intersect(player)){
this.scene.removeChild(this);
player.countDown = 15;
}
The within method is similar to the intersect method in that it also checks when a sprite is intersecting. The difference is that within also takes in a parameter distance and only returns true if the center points of the two sprites are less than or equal to that distance.
i.e.) within(SOME_SPRITE, SOME_DISTANCE) to return true when sprite’s center and SOME_SPRITE’s center are less than or equal to SOME_DISTANCE
onenterframe
function under 06.3 Within, add:
if(this.within(player, 10)){
this.scene.removeChild(this);
player.countDown = 15;
}