I am working on a game in Javascript in which I have a player try to collect coins. Both are currently rects() with different dimensions, and I am trying to incorporate a function that alerts the user when they have gotten a coin. Currently, this is my code for my player & coin collision detection.
isTouching(player) {
return player.x + player.width > this.x &&
this.x + this.width > player.x &&
player.y + player.height > this.y &&
this.y + this.height > player.y;
}
However, when I loop through my coins array and check for collisions, nothing happens. Why is this? Here is my code pertaining to this:
for (let x = 0; x < 5; x ++) { coins[x].collisions(); }
and...
collisions() {
if (this.isTouching(player)) {
alert("you got a coin!");
}
}
Both my coins and player have their own class, with my coins being stored in an array.
let player;
let coins = [];
player = new Player();
for (let x = 0; x < 5; x ++) { coins.push(new Coin()); }
Even when the player touches the coin, there is no alert. How can I fix this?
P.S. I know there are many libraries capable of checking for collisions between rectangles, but I wanted to utilize my own function to check for collisions. Please let me know how/if I need to change my collision detection system.
Also, if my provided code is unclear, here is a .zip (download linked) containing my program code: https://www.mediafire.com/file/00rz1ta5s55rvzf/game.zip/file
EDIT: A comment suggested I use a library to check for collisions, which I'm technically not allowed to do, but for the sake of testing, I tried it. I imported bmoren's p5.collide2D library which worked for me in the past, and used this code (below). However, the issue still remains, and the collisions between objects is not detected at all.
New code utilizing library:
if (this.touched()) {
alert("you got a coin!");
}
touched() {
return collideRectRect(this.x, this.y, this.width, this.height, player.x, player.y, player.width, player.height);
}