What is the best way to eliminate items from an array in a side-scrolling video game?

In my gaming project, I am creating a unique experience where the player needs to collect all the words from a given array. Currently, I am utilizing the shift() method to eliminate elements, as demonstrated in the code snippet below:

if ( bX + bird.width >= words[i].x 
        && bX + bird.width <= words[i].x + 40
        && bY+bird.height >= words[i].y
        && bY+bird.height <= words[i].y + 40){

        words.shift();
    };

Here is the array being referenced:

var nouns = ["dog", "boy", "house","farm", "phone", "plane", "doctor"];
var words = [];
for (var i = 0; i < 20; i++) {  
    words.push(new word(i * 161 + 200, Math.floor(Math.random() * (400 - 10 + 1)) + 10, nouns[i])); }

However, I have encountered an issue where if the player misses the initial element of the array ("dog"), they are then unable to capture any of the subsequent elements. How can I modify this to allow the player to access the array's elements in any order?

' https://i.sstatic.net/BnYgK.png

Answer №1

The current variable being used in collision detection is i. It is utilized to choose the word being inspected.

Conversely, the method words.shift() is employed to consistently eliminate the first word from the array.

While this approach may be effective assuming the bird is consistently positioned at the far left and all words are spaced reasonably on the x-axis, a more versatile solution could involve testing all potential words in a loop and eliminating any that have been hit or have exited the screen.

There are several techniques for removing items from an array. For instance, you can utilize words.splice(i, 1) to delete words[i]. When implementing this within a loop, it's important to consider that all subsequent indexes will shift by 1.

for (let i = 0; i < words.length; ++i) {
    if (birdCollidesWithWord(words[i]) || wordWentOutOfScreen(words[i])) {
        words.splice(i, 1);
        i -= 1;
    }
}

Answer №2

    if (words[i].x <= 0){
        words.shift();

    }

This snippet of code was implemented prior to my collision detection logic. By checking if the x-coordinate of the current word is less than or equal to zero, it effectively removed the first element from the array. This allowed the game player to seamlessly progress through the levels without any hindrance, ensuring a smooth experience.

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

Array of Msqli queries

After writing my code, I was able to achieve the desired output using two functions. The first function retrieves multiple IDs associated with a user from the database: function GetApi($connection,$UserId){ global $Apicall; $Apicall = array(); ...

Exploring the world of functional programming within nested arrays

I have been shifting towards functional programming over imperative programming recently. Imagine I have a nested array data structure and my goal is to update the values of the innermost arrays. What approach would be most effective? Here is the imperat ...

Error: The validation of a JSON request failed as schema.validate is not a recognized function

As a beginner, I am currently immersed in a node.js API authentication tutorial. Everything was going smoothly until I had to refactor my code into separate files. Now, every time I send a JSON request via Postman, I keep encountering the error message "Ty ...

What could be causing the discord.js command handler to malfunction?

As I was working on developing a Discord Bot, I encountered an issue with the Command Handler while using a for loop. This is the code in Index.js: client.commands = new Collection(); const commandFiles = fs.readdirSync('./commands').filter(fil ...

Challenges with asynchronous problems related to importing models utilizing promises in conjunction with the three.js

I'm currently struggling to resolve a promise in my script. The promise needs to be resolved when a function containing 3D file imports finishes importing, but I'm unsure how to make this happen. Is there a way to receive a signal or data from t ...

Tips for transferring a calculated value from a child component to a parent component in ReactJs

In my current project, I am faced with the challenge of passing a calculated value from a child component back to its parent. The child component is designed to utilize various user inputs to compute a single value that needs to be returned to the parent. ...

When using jQuery's $.when in a loop, it does not pause for each call to finish before moving on to the next iteration of the loop

Using $.when to make AJAX calls within a loop is causing unexpected results: for ( var i = 0; i < 4; i++ ){ $.when(get_total_price("var1","var2")).then(function (v) { console.log("i= "+i); }); } The expected output should be: i= 1 i= ...

Ways to eliminate the relationship between parent and child

I am attempting to create a design featuring a large circle surrounded by smaller circles. The parent element is the large circle, and the small circles are its children. My goal is for any circle to change color to red when hovered over, but if I hover ov ...

Error when redirecting in Express due to invalid integer input syntax

After executing a PUT query in Postgres through Express, I encountered the following error message: Error: invalid input syntax for integer: "all-calls" This issue seems to be related to the line of code within the router.put function that says response. ...

When the browser's back button is clicked, no action occurs with Next/router

I am confused about why my page does not reload when I use the browser's back button. On my website, I have a catalog component located inside /pages/index.js as the home page. There is also a dynamic route that allows users to navigate to specific p ...

What are the best methods for testing a function containing multiple conditional statements?

I have a complex function that I want to showcase here, it's quite simple but for some reason, I'm struggling with writing unit tests for it. I don't need the exact unit test implementation, just a general approach or tips on how to handle i ...

Discovering the ways to declare an array type in Haskell

Creating a linked-list type in functional languages like Haskell is straightforward, as shown by the simple definition: data List a = Nil | Cons a (List a) However, I have not come across any tutorials that explain how to define your own array type from ...

React.js Component Composition Problem

I am attempting to replicate the following straightforward HTML code within a React environment: Traditional HTML <div> Hello <div>child</div> <div>child</div> <div>child</div> </div> React(working ...

Calculate the total with the applied filters

My goal is to sum the data from the Number table after applying lookup filters. The current issue is that the sum remains fixed for all values and doesn't take into account the filter. Here's the JavaScript function I'm using to search and ...

Issue with box shadow appearing incorrectly as element content increases in size while the body has an image background

After applying a box shadow to the header div, I noticed that the box shadow doesn't display properly when the hidden elements within the header are revealed. <div id="header"> <div id="logo"> <a href="#"><img src="logo.png" ...

Learning how to retrieve the ID and Title using Jquery

Hello, I'm having an issue with my UL and LI elements. They work fine with the click function, but I can't seem to get the title when trying to access it. Example: // Works fine, but can't access the title $("#list li").on('click&ap ...

Adjusting background position using incremental changes through JavaScript

Although I have a strong background in PHP coding, using javascript is a new venture for me so I hope this question doesn't sound naive. My objective is to create a button that, when clicked, shifts the background-position of a specified DIV object b ...

Is it possible to include if else logic code within a catch statement?

There's a nagging feeling within me that having logic code within a catch statement is not the right approach. For example, my catch block currently looks like this: try{ // do some stuff that throws some unexpected errors } ...

Data has not been submitted to the MongoDB database

I attempted to save form data in my mongodb database (mongodb compass). However, after submitting the form, I checked the database and found that it was empty. When I clicked the sign-up button, it only displayed curly brackets. Main file - App.js co ...

How to enable Autocomplete popper to expand beyond the menu boundaries in Material UI

Within my Menu component, I have an Autocomplete element. When the Autocomplete is clicked, the dropdown list/Popper appears but it's confined within the Menu parent. How can I make it so that the Autocomplete's dropdown list/Popper isn't re ...