Collision detection without using canvas | Sololearn: Learn to code for FREE!


Collision detection without using canvas

Hi guys, I want to make a collision detection without using canvas just with JavaScript (not JQuery or...), Is there anyone who can write a ***simple*** code (functions or algorithms) for that. I haven't written the code yet but for example imagine one shape is moving automatically and you control the second shape movement, then when it collides with the first shape, the color of first or second shape changes. (I just want the collision code) p.s. I found this related question๐Ÿ‘‡ but the answers are kinda complicated ๐Ÿ˜ƒ

8/30/2019 12:37:49 PM

Sheida Hedayati

17 Answers

New Answer



Calviีฒ ๐Ÿ˜Šthank you so much ๐ŸŒน


Gordon thanks alottt I think it's a bit close to my code๐Ÿ˜Š๐ŸŒน, but why <20 ? and how can we write change color to blue when they hit then when they separate their colors black to their first colors , instead of console.loge collided


Gordon thanks a bunch ๐Ÿ˜Š I wrote style.back... but forgot to write else๐Ÿ˜๐ŸŒท๐ŸŒน


Cbrโœ”[ ZeroCharisma ] thanks ๐Ÿ˜Š I can't do that๐Ÿ˜ but I'll look at it๐ŸŒน


Coder yesss๐Ÿ˜ they are genius like you๐Ÿ‘Œ๐Ÿ‘๐ŸŒน


Anton Böhler wow thanks alot๐ŸŒน๐ŸŒน, I should analyze it for myself ๐Ÿ˜ƒ


Mike Perkowski thanks for the new method ๐ŸŒน๐Ÿ˜Š


Anton Böhler If there weren't any circles, does this function work with any shapes? I don't think so, because it has r ๐Ÿ˜


Sheida Hedayati this could help if you can change it to JS starting from the if statement


It looks like this has already been adequately answered but I haven't seen any mention of the element.getBoundingClientRect() method. This method returns the left, top, right, bottom, x, y, width and height values in pixels for the element it is called on. It's really useful for locating the bounds and position of an element for collision detection.


collisions don't require the canvas at all, they require math ๐Ÿ™Œ collision between two circles: function circleCollision(c1, c2){ return Math.hypot(c1.x - c2.x, c1.y - c2.y) < c1.r + c1.r; } (c1 and c2 are circles with attributes x, y, r)



here collisions between circles rectangles and points:


the formula is the same as the one Anton provided. the unit of my circles are in a viewport unit vmin. in css, i have set them both of width /height 20vmin, so i know that they are of radius 10 vmin each, so the sum is 20. for changing color, just replace the report "collided" in console with setting and and add an else to handle changing their colors back.