p5.js collision detection

Key takeaways:

  • Collision detection is crucial for many applications. It determines if two objects are overlapping in a 2D space.

  • Collision detection can be implemented using simple mathematical formulas. By comparing the coordinates and dimensions of two objects, we can determine if they are colliding.

  • p5.js provides a convenient environment for implementing collision detection. Using the built-in functions and coordinate system, we can easily detect collisions between shapes in our sketches.

Collision detection is widely used in applications such as games, computer graphics, and even self-driving cars. We perform collision detection to see whether two entities are currently in collision. In 2D coordinate systems, we can use the x- and y-coordinates of the entities to perform this evaluation in real time. Here is what a collision would look like:

No collision
No collision
1 of 2

Collision detection in 2D

In 2D coordinate-based systems, where we work with the x and y coordinates of entities, we can use some conditionals to calculate whether 2 bodies (or entities) are in collision. We need both bodies’ x- and y-coordinates and the width and height. We check for overlap between these values.

f(x)={true,if x2x1+width1 and x2+width2x1and y2y1+height1 and y2+height2y2false,otherwisef(x) = \begin{cases} \text{true,} & \text{if } x_2 \leq x_1 + width_1 \ \text{and} \ x_2 + width_2 \geq x_1 \\ & \text{and } y_2 \leq y_1 + height_1 \ \text{and} \ y_2 + height_2 \geq y_2 \\ \text{false,} & \text{otherwise} \end{cases}

Where x1,y1,width1,height1x_1, y_1, width_1, height_1 represents the attributes of the first entity,

while x2,y2,width2,and height2x_2, y_2, width_2, \text{and}\ height_2 represent the attributes of the second entity.

Note: This formula works only for regular shapes with regular width and height.

Collision detection in p5.js

In p5.js, we use the 2D coordinate plane system for drawing and manipulation. Therefore, we can use the formula above to calculate whether two shapes are overlapping, i.e., in a collision.

Let’s take a look at an example below. Use your mouse to move the box.

Code explanation

  • Lines 1–15: The x1, y1, width1, and height1 variables store the coordinates and dimensions of the first box. The x2, y2, width2, and height2 variables store the coordinates and dimensions of the second box. The collision variable stores whether a collision has happened. We set it to false at the start.

  • Lines 17–33: In the setup() function, we set the variables x and y to zero initially. We set the imageMode to CENTER. This puts the image coordinates in the center instead of the top-left corner.

  • Lines 35–45: We redraw the background and image at each frame in the draw() function. We set the x and y to mouseX and mouseY respectively. These are the coordinates of the mouse pointer. Then, we draw 2 boxes (rectangles) at x1, y1, and x2, y2 respectively. We also check for collision and change the color of the second rectangle if there is a collision and show some text at the top-left corner.

  • Lines 53–61: The isCollision() function takes in the coordinates and dimensions of two boxes and returns true if there is a collision according to the equation above and false otherwise.

Let’s modify the above example and try something we might’ve seen in games. When two objects collide, they do not move through each other. Rather, they stop.

Click the “refresh” button in the bottom right corner to generate new boxes.

Code explanation

  • Lines 1–14: The variables x1, y1, width1, and height1 are initialized to store the coordinates and dimensions of the first rectangle. Variables x2 and y2 will later be defined as arrays to store the coordinates of multiple-second rectangles. width2, and height2 define the dimensions for these second rectangles. The initialization ensures that x2 and y2 will hold multiple sets of coordinates, which allows for handling numerous rectangles. The number of these boxes is controlled by numBoxes.

  • Lines 17–29: In the setup() function, we initialize the canvas environment with dimensions of 300x300 pixels. Arrays x2 and y2 are initialized to hold the x and y coordinates, respectively, for 20 (as stored in numBoxes) smaller rectangles. These coordinates are randomly distributed within the width of the canvas and up to 30 pixels in height, establishing their starting positions.

  • Lines 32–38: The draw() loop re-renders the canvas repeatedly for animations. It begins by resetting the background to a light gray color for each frame. It checks for any collisions (although this does not affect the actions within the loop as its results are not utilized to alter any condition or property). The first “main” rectangle is filled with a magenta color and drawn using its predefined coordinates and dimensions.

  • Lines 40–50: Small rectangles are drawn in a loop, each filled with a turquoise color. The isCollision function is called within an if condition to check each small rect against the main rect for overlap, preventing them from moving downwards if they collide with the main rectangle or beyond a specific boundary, i.e. height of the screen.

Conclusion

Collision detection is an essential mechanic in almost all games. While we covered one type of collision detection today, there are more advanced types of collision detection for more complex applications (e.g., bounding circles, pixel-perfect). p5.js’ coordinate system makes it simple to implement this mechanic.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


Is p5.js good for making games?

Yes, p5.js is a good choice for creating simple, interactive games, especially for beginners. It provides a range of functions for drawing graphics, handling animations, and managing interactions, making it ideal for developing 2D games. While it might not be suitable for highly complex games, p5.js is popular for game prototypes, learning game development, and interactive web-based experiences.


How to detect collisions in Scratch?

In Scratch, collision detection can be achieved using the built-in touching blocks. This can be useful for creating game interactions, like when a character hits an obstacle or collects items.


What is p5.js used for?

p5.js is primarily used for creative coding, data visualization, interactive art, and educational purposes. It is an open-source JavaScript library designed to simplify the process of drawing graphics, handling animations, and building interactive applications, making it ideal for artists, educators, and developers working with web-based visuals.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved