+ 1
How to make collision detection with circles in JS?
For example: the radius of Circle1 = 5 and the radius of Circle2 = 10 How can i check if they collide?
9 Answers
+ 4
@jesse New Live Stream on The Coding Train talking about physics engines with some examples of matter.js Looks easy and is doing collision detection and much more.
is overkill for just two circles but you may want to consider it for future, more complex projects.
+ 3
calculate distance between the center of the two circles: the hypotenusa of the triangle defined by the horizontal and vertical difference between the circles position.
You can go through Pythagora's theorem
hyp=sqrt(deltaX*deltaX + deltaY*deltaY)
where deltaX = Circle2.x - Circle1.x;
and deltaY= Circle2.y - Circle1.y;
x and y are the coordinates of the Circles centers.
or simply use a built in function(based on the same theorem):
distance=Math.hypot(Circle1.x-Circle2.x, Circle1.y-Circle2.y);
if such distance is less than the sum of the two radiuses (in your case 15) means that the two circles are overlapping, ergo they collided.
if (distance<= Circle1.rad+Circle2.rad){
alert("COLLISION");
+ 2
@seamiki Math.hypot(); doesn't work on SoloLearn.
+ 2
If you don't want to go all the way back to Pytaghora, I suggest you to use p5js which works in the Code Playground.
Here is a nice set of tutorials by Daniel Shiffman The one linked is about collision of 2 circles.
https://m.youtube.com/watch?v=uAfw-ko3kB8
+ 2
@seamiki I already knew the coding train I wanted to make his p5.js attraction and repulsion project in normal JS
+ 2
@Jesse So, Pythagora is your answer
+ 2
@seamiki Or
var distance = dist(this.x,this.y,other.x,other.y);
in p5.js
0
@seamiki hypot is not a method of Math