Enchant.js Guide

by Patrick Casao, Cal Poly


06 Collision Detection

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


06.01 - A Word on Collisions

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.


06.02 - Using Intersect

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.)

CODE EXAMPLE: Adding the Intersect Method

Add this to the Projectile class's onenterframe function under 06.2 Intersect:

if(this.intersect(player)){
	this.scene.removeChild(this);
	player.countDown = 15;
}
	
Now the player sprite should react to the collision with the projectile sprite, and the projectile sprite should remove itself from the scene upon contact with the player. Confirm that the collision detection works by clicking on the RUN button and testing it.

You’ll probably notice that the sprite reacts to the face a bit earlier than it should. This is because the bounding box of the player sprite is actually larger than the visible sprite shows. We can avoid this premature collision by resizing the sprite or by using the within method. This method is described in the next subsection.


06.03 Using Within

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

CODE EXAMPLE: Adding the Within Method

Begin by removing or commenting out the code added from the previous section. Once again, in the Player class's onenterframe function under 06.3 Within, add:
 
if(this.within(player, 10)){
	this.scene.removeChild(this);
	player.countDown = 15;
}
	
Now the player sprite should detect the collision once its within the defined range. Confirm that the collision detection works by clicking on the RUN button and testing it.

In the next section we will discuss Scenes.