Reputation: 27
I have been struggling with this problem for a short while now and I'd love some help. So basically heres the situation. I have multiple squares that are all (100 by 100) moving up a canvas and after some time reset again to the bottom. I also have a controllable cube (20 by 20) that moves left and right. The goal of the game is to dodge the cubes until a certain time limit is reached. But I cannot for the life of me get the collision detection for the "spaceship" and the squares working. Does anyone have any ideas? Here's some code of mine that was already somewhat successful in doing it (only the left side of the "spaceship" hitting the other cubes registers).
for(var n = 0; n < block.length; n++){
if(y > block[n].y && y < (block[n].y + 100 )){
console.log(y + 100 + " " + "y check1");
if(x > block[n].x && x < block[n].x + 100){
x += 20;
console.log(x + 100 + " " + "x check1");
}
}
}
Note: x
and y
= the position of the ship,
block.y
and block.x
= the position of the blocks continuously looping to check.
I can provide the rest of my code if needed. Thanks!
Upvotes: 0
Views: 56
Reputation: 756
Here is a basic collision detection. Interestingly it's not really looking for a collision but gaps between the objects. No gap, it's hit.
if (rect1.x < rect2.x + rect2.width &&
rect1.x + rect1.width > rect2.x &&
rect1.y < rect2.y + rect2.height &&
rect1.height + rect1.y > rect2.y) {
// collision detected!
}
Upvotes: 1