javascript - Canvas collision? -
testing game , when user , monster collide want alert pop no luck:
function die() { (var = 0; < monster.length; i++) { if (user.destinationx === monster[i].destinationx && user.destinationy === monster[i].destinationy { alert("die"); } } }
i'm going provide merged answer explanation. if explanation, credit either karaxuna or user2317489.
your problem is, kolink mentioned, pacman glitch, or rather, fact monsters not pixels - have size of own. checking origin of 1 object , seeing if equal entity's - rarely, if ever, case. instead, need check if monsters have @ least 1 common point (in other words, collision checking).
this can trivially done checking if origin of 1 inside bounding box of other, or in other words, if monster2.x <= monster1.x <= (monster2.x+monster2.width)
, monster2.y <= monster1.y <= (monster2.y+monster2.height)
. code arnelle balane has provided without explanation that.
this not approximation, blindly assumes monster square. make circle, you'll need check if centre of 1 monster within distance of other centre (where distance metric, , calculated using sqrt(pow(x,2)+pow(y,2))
. finer details, though.