Тёмный

Collision Detection Between Circles in JavaScript 

Franks laboratory
Подписаться 82 тыс.
Просмотров 15 тыс.
50% 1

This is probably the easiest and the most useful algorithm you should learn if you want to create awesome games and JavaScript animations. Collision detection between circles in JavaScript first calculates the distance between two centre points and compares it to sum of radii of these two circles. Let me show you everything you need to know about detecting circle collisions and show you some awesome projects you can build with it. It's time to talk about Pythagorean theorem! :)
⭐️TABLE OF CONTENT ⭐️
00:00 Why do we need collision detection
00:30 How to detect collision between 2 circles in JavaScript
01:30 How to measure distance between 2 points
03:00 Pythagorean theorem explained
04:17 Comparing distance and radius to determine the outcome
❤ Related Links ❤
Pythagorean Theorem: Proof, Applications and JavaScript Code (Radu) • Pythagorean Theorem: P...
Art by bevouliin.com/
You can practice techniques we learned to day in these vanilla JavaScript game tutorials:
Particle trail effect: • HTML5 Canvas CRASH COU...
Fish game: • JavaScript 2D Game Tut...
🎮 Game Development MASTERCLASS SERIES with vanilla JavaScript, basics for beginners: 🎮
🐶 Project 1: Sprite animation • Sprite Animation in Ja...
🐶 Project 2: Parallax backgrounds • Parallax in JavaScript...
🐶 Project 3: NPC movement • How To Code Flying Cre...
🐶 Project 4: Rectangle collision • Collision Detection Be...
🐶 Project 5: ** this video **
🐶 Project 6: Triggered event based animations • Audio Visual Effects i...
🐶 Project 7: Raven game • JavaScript Shooter Gam...
🐶 Project 8: Enemy types • How To Code Creatures ...
🐶 Project 9: State Management • State Management in Games
🐶 Project 10: Easy Side-Scroller Game • JavaScript Side Scroll...
For most projects all we need is simple collision detection algorithm between two rectangles or between two circles. For more complex shapes, we can also use collision detection technique called separating axis theorem. It can be used to detect collision between convex polygons or rectangles that are rotated and aren't axis aligned.
🔥 I really like these GAMEDEV and GAME ART courses on Udemy 🔥
☕ How to Program Games: Tile Classics in JS for HTML5 Canvas bit.ly/2ZUfKuG
☕ Learn Professional 2D Game Graphic Design in Photoshop bit.ly/2SpPdE8
☕ The Ultimate 2D Game Character Design & Animation Course bit.ly/3eoZWqT
☕ Produce Professional Pixel Art for Your New Game bit.ly/3nUrTKm
Get Adobe creative suite apps (Photoshop, Illustrator etc.) bit.ly/3e60cI0
🎮 More HTML5 canvas and JavaScript game tutorials:
• Game Development with ...
If you are a BEGINNER you can still create beautiful animations, here is a selection of my beginner friendly projects, where I go slower and take time to explain things:
• Front End Web Developm...
If you feel more confident in your coding skills, check out some more ADVANCED ANIMATIONS with vanilla JavaScript & HTML5 canvas:
• Creative Coding with V...
Let's be friends
👍 You can message me on TWITTER / code_laboratory
👍 Check out some of my source code on CODEPEN codepen.io/franksLaboratory
Music: (RU-vid audio library) Vacay In Fiji Riddim - Konrad OldMoney
The description of this video may contain affiliate links, which means that if you buy one of the products that I recommend, I'll receive a small commission without any additional cost for you. This helps to support the channel and allows me to continue making videos like this. Thank you for the support!
#frankslaboratory

Опубликовано:

 

22 июл 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 111   
@Frankslaboratory
@Frankslaboratory 3 года назад
Hi Coders, do you study coding in school, as a hobby at home or do you work as a developer? Have you used some collision detection algorithm before? For what project?
@skarbazalam4284
@skarbazalam4284 3 года назад
yes i am done collision effect in physics also in css some concept but not as much in JavaScript now we can learn bcoz of u
@Frankslaboratory
@Frankslaboratory 3 года назад
@@skarbazalam4284 Good to know you already have some experience. I will use this technique for some cool games I'm releasing soon, wanted to make it a separate video becuase it's useful for so many projects :D
@Xyzzzz307
@Xyzzzz307 3 года назад
Hobby at home. I use all these rectangle and circle collision methods in all games. Eagerly waiting for your video on polygons collision detection
@unknown-bx8my
@unknown-bx8my 3 года назад
I just learn programming ,js and html5 canvas on internet from awesome people like you for free.😍😍😍😍😍
@Xyzzzz307
@Xyzzzz307 3 года назад
@@unknown-bx8my Learning from Web is not so easy right?
@laverico
@laverico 3 месяца назад
Wow, we just actually learned about the phytagorean theorem last quarter. Weird coincidence, but kinda funny haha.
@agent-33
@agent-33 3 года назад
Wow! The visual presentation is superb.
@Synthwave89
@Synthwave89 3 года назад
What an underrated channel! Love your videos man, keep up the good work.
@Frankslaboratory
@Frankslaboratory 3 года назад
Mario! Thank you
@gustavojuantorena
@gustavojuantorena 3 года назад
Best explanation for this topic on RU-vid. Thank you.
@Frankslaboratory
@Frankslaboratory 3 года назад
Gustavo! Thank you :)
@luismendes8238
@luismendes8238 2 месяца назад
the best tutorials i have ever seen!!! thank you for so much high quality content!!!
@Frankslaboratory
@Frankslaboratory 2 месяца назад
Hi Luis, glad you found some value
@Web-Dev-Codi
@Web-Dev-Codi 3 года назад
Another great JS tutorial and right to the point. Superb explanations as always.
@Frankslaboratory
@Frankslaboratory 3 года назад
Brian! Wow, that's a really good feedback, thank you
@jfirestorm44
@jfirestorm44 3 года назад
You can also use Math.hypot() in place of Math.sqrt(). So your distance variable would look like Math.hypot(dx, dy). No need to square dx and dy this way.
@Frankslaboratory
@Frankslaboratory 3 года назад
That's a great point and I wish I mentioned that in the video, thank you for sharing with us
@johnsmith1789
@johnsmith1789 11 месяцев назад
let cSq = a**2 + b**2;
@Frankslaboratory
@Frankslaboratory 11 месяцев назад
Hi John. Yea that's a good one as well thanks
@blessedpigeon6304
@blessedpigeon6304 6 месяцев назад
whyyyy would there be a built-in function for such a simple math operation is beyond me
@faizey
@faizey 3 года назад
Incredibly presented
@Frankslaboratory
@Frankslaboratory 3 года назад
Really? Thank you :)
@aravindvv2276
@aravindvv2276 3 года назад
As always awesome 🥳🥳 informative
@Frankslaboratory
@Frankslaboratory 3 года назад
Aravind! Thank you :D
@Undefined-id1dt
@Undefined-id1dt 3 года назад
This is great! Pls make more videos with trigonometry, since it's intresting and useful in many ways.
@Frankslaboratory
@Frankslaboratory 3 года назад
Yeah. I used a bit of sin/cos in my character animations video last week but I want to go more in depth. Trigonometry is useful for so many things
@drkmgoswami3042
@drkmgoswami3042 3 года назад
Waiting for video on circle and rectangle collision detection
@Frankslaboratory
@Frankslaboratory 3 года назад
Collision between circle and rectangle? Interesting. I might do that as well.
@evaristocuesta
@evaristocuesta 3 года назад
A very useful tutorial!
@Frankslaboratory
@Frankslaboratory 3 года назад
Thank you Evaristo
@aliciapeter562
@aliciapeter562 2 года назад
Great video Franky , Thanks
@Frankslaboratory
@Frankslaboratory 2 года назад
Hi Alicia. Glad you liked it. Nice to meet you
@aliciapeter562
@aliciapeter562 2 года назад
@@Frankslaboratory Do you have some video how to make jump with ball in canvas ? can you please share link ? Thanks
@jovannyswicktutorials9960
@jovannyswicktutorials9960 9 месяцев назад
These are good. We could avoid the sqrt by storing circle1.r^2 and circle2.r^2 inside their own instances. Then you could compare triangles h^2 < circle1.r^2 + circle2.r^2.
@rajesht9702
@rajesht9702 3 года назад
Thank you Franks Laboratory for making very useful video with basic Maths. I Really appreciate it.
@Frankslaboratory
@Frankslaboratory 3 года назад
You are welcome Rajesh :)
@JM-de2gh
@JM-de2gh 3 года назад
Hey Frank, sorry I disappeared for a long time. I caught up on all your vids as of now! Very well done! I think another really neat thing to show people is Lerping. I think you've mentioned in your videos in the past: function lerp(initial, final, factor) { return initial + (final - initial) * factor }
@Frankslaboratory
@Frankslaboratory 3 года назад
Hi Jon, it's been a while, hope you are enjoying the spring. Good to see you here again, I have a lot of ideas for linear interpolation, thank you for reminding me. I think my audience prefer when there is a project at the end of video, still not sure how to do this short video format. Thanks for giving me ideas.
@JM-de2gh
@JM-de2gh 3 года назад
​@@Frankslaboratory I personally don't mind short or long videos (short videos every week or long videos every two to three weeks). But I have a gut feeling your channel has grown because your original videos show a complete process from beginning to end. It's your projects that originally grabbed my attention. I don't know how I would have responded if your channel only had singular mechanics... hummm.
@rezwansaki
@rezwansaki Год назад
Thanks
@debarghyabanerjee5
@debarghyabanerjee5 3 года назад
Tq for the video
@Frankslaboratory
@Frankslaboratory 3 года назад
Hi Debarghya, I'm here to help
@nicklansbury3166
@nicklansbury3166 3 года назад
Frank's Fridays ftw 🥳
@Frankslaboratory
@Frankslaboratory 3 года назад
I like to give people something to watch for weekends haha. Happy Friday Nick :)
@jeffreygonzalez5045
@jeffreygonzalez5045 Год назад
OH, this makes so much sense.
@Frankslaboratory
@Frankslaboratory Год назад
Glad you found some value Jeffrey
@karamelhaj
@karamelhaj 2 года назад
You can calculate the distance between the center of the cirlcs like this ( (x1-x2)**2 + (y1-y2)**2 )**0.5
@Frankslaboratory
@Frankslaboratory 2 года назад
Nice, ** is exponentiation operator introduces in ES2016, I haven't used it yet, thanks for this tip
@dinoDonga
@dinoDonga 3 года назад
This series is great. Trigonometry was always my strongest area in math but sadly i disliked it during school. If someone had taught it to us like you do in these videos i am sure more people would have discovered how satisfying this can be. Maybe release a mini library "frank.js" or "fLab.js"
@Frankslaboratory
@Frankslaboratory 3 года назад
Thank you Leon :) I never used to like trigonometry in school until I realised it can be used for animations. I like the idea of making a library. If I had more time I would do a course where we build that library from scratch
@gael3001
@gael3001 4 дня назад
Hi good afternoon this content is awesome. I have a problem, I try to make a collision between one rectangle controled for me and some rectangles created by classes but I can't to do it. The code includes forEach for update the movement of each one rectangles. I tried many ways to do it.
@wesleytong7049
@wesleytong7049 3 года назад
Hey Frank! I'm working on a small scrolling platformer game, and your tutorials have been super helpful, especially that of the collision videos and parallax scrolling. However, I'm having trouble figuring out how to incorporate collision detection in a scrolling game. How were you able to incorporate collision detection into your scrolling game? Did you use collision maps that were the same size as the layer images? Thanks!
@Frankslaboratory
@Frankslaboratory 3 года назад
Hi Wesley, I'm not sure what collision maps are, will google it. Oh do you mean tile maps? I haven't build a platformer game here on the channel yet, my sidescrollers don't have platforms player can jump on. There is a good article on tilemaps on MDN, that describes the technique. For collision between player/enemies/obstacles it's simpler, you just keep them in arrays and run collision detection between player and enemies array for example, it doesn't matter if the game is static or scrolling, the functionality doesnt change.
@wesleytong7049
@wesleytong7049 3 года назад
@@Frankslaboratory I see, yeah I'm trying to figure out how to create multiple long platforms that scroll along with the background, but am having trouble implementing it using the requestAnimationFrame function. Thanks!!
@unknown-bx8my
@unknown-bx8my 3 года назад
Great tutoriol and very useful. MATH + PROGRAMMING = 🔥🔥🔥🔥 Can i know what's the next collision detection video is about? I am very interesting.
@unknown-bx8my
@unknown-bx8my 3 года назад
@@Frankslaboratory thank you, i am waiting you to make advanced videos about collisions because i dont know how to detect all collisions. This series will be awesome. I am just waiting☺🖒
@randirelander5639
@randirelander5639 Год назад
Kind of late to the party here, and it was kind of mentioned in one of the other posts, but here is a method without the use of square roots or fractional exponents: Looking at the Pythagorean diagram at 3:39 in the video, we actually have a collision when the area of the orange square plus the area of the blue square (distance squared) is less than the area of the white square (sum of radii squared). Another way to look at it is to square both sides of the comparisons on lines 10 and 12 in the original algorithm at 4:39 in the video. let distanceSquared = dx * dx + dy * dy; let sumOfRadiiSquared = sumOfRadii * sumOfRadii; if (distanceSquared < sumOfRadiiSquared) { // circles collide } else if (distanceSquared === sumOfRadiiSquared) { // circles are touching } else if (distanceSquared > sumOfRadiiSquared) { // no collision }
@sakshikumari3620
@sakshikumari3620 8 месяцев назад
On 2:50 Sir I think 🤔 dy would cirlce1.y - circle2.y because Circle 1 is further than circle 2. In y coordinate As you have done in finding dx that Circle 2 , in x coordinate.
@Xyzzzz307
@Xyzzzz307 3 года назад
Sir 🤯🤯. I think all self taught Programmers who like creating and playing Games are also Lovers of Space. I am a Mars Lover. Is it for all?
@Frankslaboratory
@Frankslaboratory 3 года назад
I like space actually, I watch a lot of space documentaries and place space video games :D
@Xyzzzz307
@Xyzzzz307 3 года назад
@@Frankslaboratory That means it is true that 😛
@nmastepankaj
@nmastepankaj 3 года назад
sir, please make video on webGL or three.js particle system. I want to make person image using particle in 3D and rotate in 3D looks amazing and apply to my portfolio website.
@nmastepankaj
@nmastepankaj 3 года назад
sir please also make ripple effect using webGL same as in jQuery library ripple.js. I actuallay hate library. It increase the loads over website.
@Frankslaboratory
@Frankslaboratory 3 года назад
I want to do some webgl with vanilla JS. Its quite advanced. That ripple effect can also be done with 2d canvas I think.
@quietnix
@quietnix 3 года назад
Instead of square rooting every time, you can square the sum of radii one time, it will be more efficient.
@Frankslaboratory
@Frankslaboratory 3 года назад
That's a great point Nikhil, yes this technique you described combined with object pooling will allow us to calculate sum of radii only once and keep it stored somewhere, for example. Good optimization idea.
@genuinobrasileiro
@genuinobrasileiro Год назад
hi, nice videos... how to do this kind of math to array of circles? if I have a lot of circles on the screen
@Frankslaboratory
@Frankslaboratory Год назад
Just run the checks in a for loop that cycles though all elements, you can also create a reusable function like this, this one in particular is from my upcoming game dev class checkCollision(a,b){ const dx = a.x - b.x; const dy = a.y - b.y; const distance = Math.hypot(dy, dx); const sumOfRadii = a.radius + b.radius; return (distance < sumOfRadii) } and then you just run this code like this this.circles.forEach(circle => { if (this.checkCollision(player, circle)){ // code to run when collision happens } }); With a reusable function like this we have to make sure that all elements we pass as a,b arguments have all necessary properties, in this case x, y and radius. I will explain it step by step in my new game dev series, this code snippet might look complicated. We will be using this technique a lot for a couple of games.
@genuinobrasileiro
@genuinobrasileiro Год назад
@@Frankslaboratory hey man, thank you for the wonderful answer... Thank you so much😀
@sidheshwartiwari9834
@sidheshwartiwari9834 3 года назад
🙏🏻
@Frankslaboratory
@Frankslaboratory 3 года назад
🙏♥
@Xyzzzz307
@Xyzzzz307 3 года назад
Hi Sir. Do you code only in html5?
@Frankslaboratory
@Frankslaboratory 3 года назад
I use HTML, CSS and JavaScript, I don't know any other programming language (yet)
@Xyzzzz307
@Xyzzzz307 3 года назад
@@Frankslaboratory You can get familiar with other languages very easily
@bananaeater4332
@bananaeater4332 7 месяцев назад
Suppose there are two circles, one stationary and the other moving like a ball, while the stationary (that only moves to right and left upon click of the right and left key) circle acts as a flipper or goalkeeper in a 2D game. I have noticed that the current approach only detects the collision of the ball within the center of the stationary circle, and not with its edges. This is a concern for me, and I would appreciate any help in understanding why this is happening.
@Frankslaboratory
@Frankslaboratory 7 месяцев назад
This approach detects when two circles overlap (radius 1 plus radius 2 is more than distance between their centrepoints), when they touch (radius 1 plus 2 is exactly the same as the distance) and when they don't collide ( radius 1 plus 2 is less than the distance). This is all you need. If not, try to explain what you mean better please.
@bananaeater4332
@bananaeater4332 7 месяцев назад
Thank you for your response. I understand and agree with your explanation about circle collision detection. However, in my recent project, a pinball simulation using vanilla JavaScript, I encountered some challenges with this approach. The issue seems to arise particularly at higher velocities or under varying speed conditions of the ball. In these scenarios, I observed that the ball sometimes passed through the circles, got stuck on them, or the collision was detected only when the ball overlapped significantly with the circle. It appears that the standard method of detecting collisions based on the sum of radii and distance between centers is less effective when dealing with fast-moving objects or variable speeds. Any insights or suggestions on handling these high-velocity scenarios more accurately would be greatly appreciated.@@Frankslaboratory
@Frankslaboratory
@Frankslaboratory 7 месяцев назад
@@bananaeater4332 can you show me the lines where you calcutate dx dy sumOfRadii and distance from the project that you say doesn't work. This calculation will happen once per animation frame, it's reliable for high speeds. How are you resolving those collisions and what system are you using to tell you the collisions are detected or not detected, because in these high speeds I'm sure you don't just rely on your eyes.
@Frankslaboratory
@Frankslaboratory 7 месяцев назад
If you say the balls get stuck in each other, there is some additional code to resolve the collisions. I don't cover that in this video, the solution to your problem is in that part of your codebase
@coltonaallen
@coltonaallen 3 года назад
Hey, frank, I hope you're doing well. It's been a while, and I've missed a few of your videos that I gotta catch up on. But I've been busy creating a portfolio and growing my web dev skills. I just wanted to let you know that I just received a job offer was a front end web developer yesterday and I've accepted, do I'm now a fully fledged web developer, and I wanted to thank you for your videos And tutorials. I accredit a lot of my knowledge to your excellent videos, and I just wanted to say thank you. Also, I used some canvas particles effects on my portfolio. Lol I can't wait to catch up on your latest vids!
@Frankslaboratory
@Frankslaboratory 3 года назад
Arthur! Is that your first web dev job? If so that's great news, exciting time for you :D Getting the first job is always the most difficult, your life will never be the same now :D What frameworks does your company use, React/Angular?
@coltonaallen
@coltonaallen 3 года назад
@@Frankslaboratory Thanks! This is my first Dev position, and I am super excited! The company is a marketing and design company with different packages depending on how elaborate the client wants their site, which ranges from WordPress to custom builds. Not too familiarized with exact tech stacks yet, but they were impressed by my take-home assignment they gave, in which I used plain vanilla JavaScript and Sass, that they feel confident I can learn their stack quickly. Also, they're looking for candidates who will bring new tech to the table, and I love using React, so they liked that too. Thanks for the vids and encouragement along the way! Always a joy to watch your tutorials!
@youtoshorts4720
@youtoshorts4720 Год назад
Why doesn’t work on codehs
@Frankslaboratory
@Frankslaboratory Год назад
What is codehs
@youtoshorts4720
@youtoshorts4720 Год назад
@@Frankslaboratory codeing program a lot if schools use
@JUNGELMAN2012
@JUNGELMAN2012 Год назад
better numbers in the beginning: var circleYELLOW = {x: 200, y:600, radius: 150}; var circlePINK = {x: 400, y: 200, radius: 80}; else you see only part of the circle if you use var circleYELLOW = {x: 10, y:10, radius: 300};
@papiermuecke7626
@papiermuecke7626 Год назад
One thing that irritates me is, that in this case you had actually a perfect right triangle. But imagine you would move the other circle a bit further down and into the right, you dont have a right triangle shape anymore and that results that you can not use pythagoras anymore, right?
@Frankslaboratory
@Frankslaboratory Год назад
Thank you for asking this because it shows me that the visual is not that good. The triangle will always be right. There will always be 90 degrees regardless or size of the circles or where they sit in relation to each other. You can always use pythagoras theorem. I will make a new animated visual to show this for my new videos.
@qwe-rty-
@qwe-rty- 3 года назад
It's ok but the point is the circle...
@NileshDadheech
@NileshDadheech 3 года назад
Hello sir My channel has monetized 😊 (Spiderman effect)
@Frankslaboratory
@Frankslaboratory 3 года назад
Hi Nilesh, congratulations :D You provide a lot of valuable content on your channel, I like your latest border animation video, very creative.
@NileshDadheech
@NileshDadheech 3 года назад
@@Frankslaboratory thank you!!😊💓
Далее
Audio Visual Effects in JavaScript Games
24:43
Просмотров 18 тыс.
Creative Coding Math: Collision Detection
15:45
Просмотров 1,8 тыс.
Collision Detection Between Rectangles in JavaScript
5:53
State Management in Games
1:09:09
Просмотров 54 тыс.
Parallax in JavaScript Games
43:42
Просмотров 47 тыс.
Can you guess a shape from its shadows?
9:01
Просмотров 455 тыс.
6 Levels of Thinking Every Student MUST Master
17:12
Просмотров 1,2 млн
Simulating the Evolution of Rock, Paper, Scissors
15:00
This is Why Programming Is Hard For you
10:48
Просмотров 709 тыс.
Using AI to Create the Perfect Keyboard
12:05
Просмотров 1,4 млн
Collision Detection (An Overview) (UPDATED!)
7:27
Просмотров 34 тыс.