Question: how to detect a collision? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Question: how to detect a collision?

Question: how to detect a collision. in the js file i create two squares one blue and one red, the red one stays still and the other blue one moves towards red. how can i detect a collision of both squares? detail: all this in two basic files for the web, html and a javascript file.

3rd Dec 2022, 7:26 PM
Pensador_R
Pensador_R - avatar
3 Answers
+ 3
Assuming you are using canvas to draw . You already know the postion of red and blue . Also when the blue one is moved it's new position is known . Now you just need to check if the red square right side(x coordinate) equals to blue square left side (x coordinate) .
3rd Dec 2022, 8:22 PM
Abhay
Abhay - avatar
8th Dec 2022, 11:11 AM
Calviղ
Calviղ - avatar
+ 2
So you try to detect when blue square are next to red? You need to track positions of blue square to calculate when it touch red. If you have fixed size container you can know how much pixels blue square need to move. You need to know in pixels: size of container, position of red box and its size, and to track current position of blue box and size of blue box If you make game try using canvas or some library for making games(library may have useful methods), also check some tutorials This is snake game, this game need to implement logic you ask for, so I suggest you to watch https://youtu.be/baBq5GAL0_U
3rd Dec 2022, 8:15 PM
PanicS
PanicS - avatar