简体   繁体   中英

Collision detection between two squares in javascript

I've got a problem in my code, I can move the red one (square1) by clicking on it,what I want to do is to detect a collision when the red one touch the blue one. I want it to change colour when there is a collision...

Here is my code to be more clear: http://jsbin.com/iFAlIyIv/4/edit

Your basic approach was right, the problems were things like this:

  • Instead of square1.left , you want square1.offsetLeft . Elements don't have a left property. Same goes for top , width , and height .

  • Instead of document.getElementById("square2") , you need to select the element by class name, since there's no element with that ID (only an element with that class).

  • You're calling changecouleur , but you probably meant to call colorswap . Looks like a bit of unfinished refactoring.

You also don't need any of the additional checks after this:

if (bl > ar || br < al) {
    return false;
} //overlap not possible
if (bt > ab || bb < at) {
    return false;
} //overlap not possible

If neither of these conditions are true, they must overlap.

http://jsbin.com/iFAlIyIv/13/edit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM