How to calculate the distance between two points using JavaScript and p5.js?
Calculating the distance between two points on the canvas is an important concept when working with graphics.
There are tons of scenarios where you need to know this distance. Here are just a couple of examples:
-
In game development, you can use the distance between two objects' hotspots to implement simple collision detection. If the distance between the two hotspots is getting close to zero, it is likely that the objects are colliding.
-
In programs that involve mouse interaction, it is often necessary to measure the distance between the mouse cursor and objects on the canvas. This can be used to determine how close the mouse is to a particular object, for example, and trigger different actions based on the distance.
In both of these scenarios, accurately calculating the distance between two points can be essential for creating a smooth and functional user experience.
The math part
To calculate the distance between two points on a canvas in JavaScript, you can use the Pythagorean theorem. The theorem states that in a right triangle, the square of the length of the hypotenuse (the side opposite the right angle) is equal to the sum of the squares of the lengths of the other two sides.
To use this theorem to calculate the distance between two points (x1, y1) and (x2, y2), you can use the following formula:
distance = Math.sqrt((x2 - x1)^2 + (y2 - y1)^2)
Here's an example of how you might use this formula in a JavaScript function to calculate the distance between two points on a canvas:
What about p5.js
If you're using a coding environment such as codeguppy.com that uses the p5.js library, or if you're just building p5.js sketches, you don't even have to define the above distance
function.
p5.js comes with a built-in function called dist
that does the same thing.
Let's update the program and notice the same effect.
Happy coding!
Read more blog articles Browse JavaScript projectsAbout codeguppy
CodeGuppy is a FREE coding platform for schools and independent learners. If you don't have yet an account with codeguppy.com, you can start by visiting the registration page and sign-up for a free account. Registered users can access tons of fun projects!
Follow @codeguppy on Twitter for coding tips and news about codeguppy platform. For more information, please feel free to contact us.