+ 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?

3rd Mar 2017, 4:53 PM
Jesse
Jesse - avatar
9 Réponses
+ 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.
5th Mar 2017, 9:09 PM
seamiki
seamiki - avatar
+ 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");
3rd Mar 2017, 7:26 PM
seamiki
seamiki - avatar
+ 2
@seamiki Math.hypot(); doesn't work on SoloLearn.
4th Mar 2017, 10:22 AM
Jesse
Jesse - avatar
+ 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
4th Mar 2017, 12:54 PM
seamiki
seamiki - avatar
+ 2
@seamiki I already knew the coding train I wanted to make his p5.js attraction and repulsion project in normal JS
4th Mar 2017, 2:32 PM
Jesse
Jesse - avatar
+ 2
@Jesse So, Pythagora is your answer
4th Mar 2017, 3:01 PM
seamiki
seamiki - avatar
+ 2
@seamiki Or var distance = dist(this.x,this.y,other.x,other.y); in p5.js
4th Mar 2017, 3:04 PM
Jesse
Jesse - avatar
0
@seamiki hypot is not a method of Math
3rd Mar 2017, 9:44 PM
Jesse
Jesse - avatar