Updating previous values in an array using Javascript's splice

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();

Answer №1

Encountering issues while modifying an array during a loop is a common occurrence.

For instance, removing an item at position i will cause the subsequent items to shift left, resulting in the next item occupying position i. However, since the next iteration of the loop examines i+1, that item will be skipped!

To address this, one can either use i--; after splicing to ensure inspection of the new item at position

i</code in the next iteration, or simply loop backwards to prevent complications from operations affecting the remainder of the list.</p>

<pre><code>for(var i = currentGame.items.length; i--; )

Additionally, I noticed something concerning in your code:

position = currentGame.items.indexOf(i);

Shouldn't we already know that the position of the current item is i? The indexOf function searches for an item with the value

i</code in the list. It is likely that <code>position
will receive a value of -1 if the search using indexOf fails. I believe what you intend to do here is:

var position = i;

Lastly, if you are not a fan of

console.log</code, consider inserting the following into your if block:</p>

<pre><code>debugger;

This manually sets a breakpoint in your code so you can examine the variable values and identify any issues. Ensure you have your browser's debugger or "dev tools" panel open. Remember to remove the statement once you are done debugging!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Challenges with conditional statements in JavaScript

This is a simple code snippet for a ToDo-List application. The function InputCheck() is designed to validate if the input bar contains any value. If the input bar is empty, the function should not trigger the addTodo function. However, in its current stat ...

assign a role to a discord.js user using the role stored in the client class variable

Is there a way to dynamically assign a role to a user using the client variable const client = new Client({ intents: [GatewayIntentBits.Guilds] }); instead of through an interaction? The user's role needs to be updated when a 3rd party request is rec ...

Ways to resolve issues with resizing div elements while waiting for JavaScript to load

Apologies for the lack of a clear title to describe my issue. My problem involves this snippet of code, where I am creating a label to show time to users. <div class="content"> <div class="container"> <div class="card"> < ...

Analyzing elements within an array to eliminate duplicates (PHP and MySQL)

I have a task involving PHP/MySQL that I am currently working on. At the company where I work (not in programming), we are gathering fax numbers and other data from customers to use in case of operational issues. The array structure is as follows: A ...

jQuery simplifies the syntax by using $.ajax() instead of the traditional loadXMLDoc() function to make XMLHTTPRequests

My question is: Is using $.ajax() in jQuery just a way to streamline the normal code structure? $.ajax( {url:"index.php/a", type:"POST", contentType:"application/json; charset=utf-8", data:{some_string:"blabl ...

Angular is encountering an issue where it is unable to read the value of a JavaScript function, despite the object having a value

I have developed some JavaScript functions that involve reading and writing to a JSON file, with the intention of calling them in an Angular environment (from TypeScript code) using the jsonfile library. Below is the code snippet: function savePatient(pa ...

Encountering an issue while attempting to send an image through JavaScript, jQuery, and PHP

I'm currently attempting to upload an image using JavaScript/jQuery, but I am unsure of how to retrieve the image in order to send it to a server (PHP). I have a form containing all the necessary information that I want to save in MySQL, and I use jQu ...

Verify that two variables within a multidimensional array are identical within the array

I'm working with a complex multidimensional array structured like this: array(4) { [0]=> array(3) { ["rowid"]=> int(3) ["columnid"]=> int(5) ["seattype"]=> int(10) } [1]=> ...

I seem to be having trouble getting the home page to display properly in the app, even though I believe my code is correct. I would greatly appreciate any help in identifying the mistake

I have been struggling to render the HomePage using react Router for the past two days. I would greatly appreciate any support you can provide. Despite my numerous attempts, I have been unable to solve this problem. I even tried tools like chatgpt but al ...

Troubleshooting problems with AngularJS loading data through ajax

One of the custom widgets in my application relies on Angular functionality. On a particular page, this widget is loaded via ajax. The following content is fetched through ajax and inserted into the DOM: _abc.html: <script type="text/javascript">c ...

Peculiar redirection encountered while handling a form with checkbox option

When I try to submit the form in Chrome, the PHP file does not get called and I am redirected to another HTML page. However, in Firefox, when I select three checkboxes, it redirects me to that same HTML page as in Chrome. I even tried using radio buttons i ...

Substituting a JavaScript function with a UserStyle solution

I am currently working on customizing a UserStyle for Instapaper. Since the original UserStyle was created, Instapaper has implemented several JavaScript functions in their header that control page width and font styles. Below are the functions: ...

Error in Firebase admin SDK FCM: Only one of the parameters topic, token, or condition is mandatory

I encountered an error message while trying to send FCM notifications with multiple tokens. This was working fine before, but now I'm getting the following error: 0|api | 2020-2-11 13:26:26 [ExceptionsHandler] Exactly one of topic, token or co ...

Adjustable Footer Size with Minimum Size Constraint

On my webpage, I have a footer that is not fixed in place. Currently, the page's content does not require scrolling, and the footer occupies about 25% of the browser window at full screen on a 1920 x 1080 display. The footer's contents are aligne ...

How can I reposition an image diagonally to a specific location using JavaScript in p5.js? Is there a method to display an image and then conceal it at a chosen location in p5.js?

Is there a way to move the third image diagonally until it intersects with the two images? var pic1; var pic2; var pic3; let posX=0 let posY=0 const rightwall=350; function preload(){ pic1=loadImage("5.png") pic2=loadImage("iron.jpg&qu ...

SyntaxError: Unexpected symbol

I have an issue with the following code: let op = data.map(({usp-custom-90})=> usp-custom-90 ) When I run it, I encounter the following error: Uncaught SyntaxError: Unexpected token - I attempted to fix it by replacing the dash with –, but t ...

Why aren't the validations being set when creating Angular forms using formControl.values?

I had to structure the form in a specific way in my app.ts file -> courseNameControl = new FormControl("", [Validators.required,Validators.minLength(2)]); contentControl = new FormControl("", Validators.required); form = { cours ...

What is the reason for needing to refresh when submitting form data in a Node application with an HTTP POST

Code Snippet - Angular .state('studentInfo.newStudent', { url : '/new/student', templateUrl: 'students/new-student.html', controller : function($state, $http){ this.saveStudent = func ...

Iterate through an array of strings within a paragraph tag

In my current situation, I am dealing with an array of strings and would like to iterate through it within a <p> tag if the array is empty. This is what I have so far: <p *ngIf="detailMessageMultilines">{{detailMessageMultilines}}< ...

Using Node.JS to retrieve values of form fields

I am working with Node.js without using any frameworks (specifically without express). Here is my current code snippet: const { headers, method, url } = req; let body = []; req.on('error', (err) => { console.error(err); }).on(&apos ...