问题
Not sure if I'm on the right track here, but I figured this should work:
function collides(a, b) {
return a.x < b.x + b.width &&
a.x + a.width > b.x &&
a.y < b.y + b.height &&
a.y + a.height > b.y;
}
function handleCollisions() {
$('#player').forEach(function(player) {
$('#powerUp').forEach(function(powerup) {
if(collides(player, powerup)) {
$('#player').hide();
}
});
});
}
handleCollisions();
}
Basically I have my player running around the game and the object at a fix position. When the player collides with the object he should disappear. I will provide a fiddle if needed but I figured that there is something visibly wrong with the code. Any suggestions?
Edit:
function collides(a, b) {
return a.offset() < b.offset() + b.width() &&
a.offset() + a.width() > b.offset() &&
a.position() < b.position() + b.height() &&
a.position() + a.height() > b.position();
}
function handleCollisions() {
if (collides($('#player'), $('#powerUp'))) {
$('#player').append("<p>collided</p>"); // hide player onCollision
}
}
handleCollisions();
}
`
来源:https://stackoverflow.com/questions/25374189/jquery-collision-detection