In my game development project, circles are randomly displayed on a canvas. These circle objects are stored in an array and when the player collides with one of them, I aim to remove that specific object. Below is the current code snippet for handling the collision -
for(var i = 0; i < currentGame.items.length; i++)
{
if (player1.x < currentGame.items[i].x + currentGame.items[i].radius*2 && player1.x + currentGame.items[i].radius*2 > currentGame.items[i].x &&
player1.y < currentGame.items[i].y + currentGame.items[i].radius*2 && player1.y + player1.car.height > currentGame.items[i].y) {
currentGame.score++;
position = currentGame.items.indexOf(i);
currentGame.items.splice(position, 1);
}
}
The above code functions correctly when the player collides with the last added circle in the array/canvas. However, issues arise when the player hits circles within the middle of the array, resulting in all subsequent items being removed (not the previous ones). As a consequence, the player's score increases by the number of deleted circles. This behavior indicates that upon removal of a circle, the remaining items shift down and assume the deleted circle's position, leading to collisions with multiple circles and subsequent deletions.
I am seeking guidance on resolving this issue, unsure if there is an error in how I am using the splice method.
Here is the code segment responsible for adding items to the array -
function createItem(){
item1 = new itemSmall();
item1.x = Math.floor(Math.random()*((currentGame.windowWidth - 40)-40+1)+40);
item1.y = Math.floor(Math.random()*((currentGame.windowHeight - 40)-40+1)+40);
item1.fillStyle = "rgb(200,80,200)";
item1.lineWidth = 4; //Stroke Thickness
item1.strokeStyle = "rgb(255,215,0)";
currentGame.items.push(item1);
}
The 'items' array declaration is here (extraneous content removed for clarity) -
function gameValues(){
this.items = [];
}
currentGame = new gameValues();