JavaScript: create a collision detection algorithm to find pairs of objects in an object, not an array

I'm in the process of developing a Javascript game and I'm facing the challenge of implementing collision detection.

Each element rendered in the game has its own unique ID and is stored in an object. I opted for using an object as a container instead of an array because it allows easy removal of children. In the case of a bullet hitting a ship, the object ensures that the specific element can be removed without having to shift all other elements like in an array. Additionally, having IDs for tracking purposes makes management more efficient.

When attempting to identify pairs within an array, I can follow this approach:

var a = [];
//Object container

for(var i = 0; i < a.lenght; i++){
    for(var j = i+1; j < a.lenght; j++){
        var object1 = a[i];
        var object2 = a[j];
        //collision detection
    }
}

However, when dealing with an object

var o = {};
//Object container

var progress = [];

for(var key1 in o){
    progress.push(key1);
    for(var key2 in o){
        if(progress.indexOf(key2) === -1){
            var object1 = a[i];
            var object2 = a[j];
            //collision detection
        }
    }
}
progress = [];

This method seems less elegant compared to working with arrays. Is there a more effective solution available?

Answer №1

To obtain the property names in the object, you can utilize Object.keys. The process is quite similar to working with an array:

var keys = Object.keys(myObject);        
for (var x = 0; x < keys.length; x++) {
    for (var y = x + 1; y < keys.length; y++) {
        var item1 = myObject[keys[x]]; 
        var item2 = myObject[keys[y]];
        //run collision detection here
    }
}

Keep in mind that Object.keys only includes enumerable, own properties. A for-in loop would cover all enumerable properties, including inherited ones. However, assuming that your object myObject does not have any enumerable inherited properties.

You should only use Object.keys when adding or removing a ship, not each time you perform collision detection.

It's best to conduct profiling tests to determine whether it's more efficient to work with an object and refresh the keys array upon changes, as opposed to using an array and splice.

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

Dealing with Combining Sorted Arrays in C++

I have been encountering difficulties with solving a problem that involves merging two sorted arrays, or in this case vectors. The output I am receiving when displaying the vector elements on the console is quite perplexing. Ideally, I would like to see al ...

How can I adjust the animation speed for ChartJS graphics?

Trying to adjust the animation speed of a pie chart in chartJS. Various methods have been attempted: numSteps: Number animationSteps: Number Chart.defaults.global.animationSteps = Number However, none of these approaches have successfully altere ...

Using query parameters in Angular to interact with APIs

One scenario involves a child component passing form field data to a parent component after a button press. The challenge arises when needing to pass these fields as query parameters to an API endpoint API GET /valuation/, where approximately 20 optional p ...

In iOS devices, the Ionic framework restricts the ability to open links in a new tab using the ng-href attribute

In my quest for mobile functionality, I'm aiming to implement a feature on devices where tapping will open 'codepen.io' (triggered by ng-click), and tap and hold will display a context menu with the option to 'Open In New Tab', red ...

Retrieving queries from a sibling component using react-query: A step-by-step guide

I have a question regarding how to refetch a query from another sibling component using react-query. Let's consider Component A: import {useQuery} from "react-query"; function ComponentA(){ const fetchData = async () => data //re ...

What is the best way to save an array within a pandas dataframe?

I'm trying to save an array of strings in a cell of a dataframe, but I keep getting the error ValueError: Must have equal len keys and value when setting with an iterable I initialized an empty array like this: words = [] I have some text that I want ...

The successful Ajax POST request does not result in an update to the JSON file

I am facing an issue with adding data to a *.JSON file. Despite receiving a "success" message from Ajax, the file remains unchanged. I have also noticed that when the JSON file is empty, nothing happens at all. Can someone help me find a solution? I'm ...

Executing JavaScript functions within static files in Django

I can't figure out why I'm unable to invoke a javascript function when clicking my Bootstrap button in a Django project. In my directory, I have set up the static folder as "main/static/main/js/script.js". While I can successfully load the stati ...

Accessing and fetching data from a PostgreSQL database using JavaScript through an API

I am currently working with an npm package called tcmb-doviz-kuru to fetch currency data from an API and then insert it into my database. However, I am facing an issue with mapping the data to properly insert the values. Below is my code snippet: var tcmbD ...

Creating a server that is exclusive to the application in Node.js/npm or altering the response body of outgoing requests

As I work on developing a node app, the need for a server that can be used internally by the app has become apparent. In my attempts to create a server without listening to a port, I have hit a roadblock where further actions seem impossible: let http = ...

Deleting sections of a string using JavaScript

I've encountered a rather unique issue where I need to address a bug on a website. The problem is that when a string is generated dynamically, it automatically adds 5 spaces before and after the string. Ideally, this should be fixed in the backend cod ...

Utilizing Google's GeoApi to retrieve users' location data regarding their city and country

I am currently using this code to retrieve the full address information of users function getGeo() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function (a) { $("#geoLoc").html("Determining your location. ...

Determining the quantity of items in a MongoDB collection using Node.js

Having recently delved into Node.js and MongoDB, I find myself struggling to grasp the concept of callbacks. Despite reading several articles, the topic remains confusing to me. In the snippet of code below, my aim is to retrieve the count of orders with s ...

Implementing jQuery's live() method to handle the image onload event: a guide

Looking to execute a piece of code once an image has finished loading? Want to achieve this in a non-intrusive manner, without inline scripting? Specifically interested in using jQuery's live() function for dynamically loaded images. I've attemp ...

In Angular 2, transferring data from a parent route to a child route

I have set up a route named "home" with three child routes: documents, mail, and trash. Within the home route component, there is a variable called 'user'. While I am familiar with various methods of passing information between parent and child c ...

Get rid of numerous div elements in a React.js application with the help of a Remove button

I need help figuring out how to efficiently remove the multiple div's that are generated using the add button. I am struggling to grasp how to pass the parent div's id into the delete method from the child div. Additionally, I'm wondering if ...

Running "vue ui" with Node.js v17.2.0 - A step-by-step guide

After updating to Node.js v17.2.0, I am facing issues with running "vue ui" in my project. The error message I receive indicates a problem with node modules: at Object.readdirSync (node:fs:1390:3) at exports.readdir (/usr/local/lib/node_modules/@vu ...

Generating a component of a structure array by utilizing a function that takes a pointer to the structure

Struggling to create a function that modifies a struct array with pointer. Want the array to have an additional struct element after calling this function. Here's the revised version of my function based on your advice: void addPic(pic *picture_Reco ...

Transforming multi-layered form data into a JSON array structure for seamless integration with application/json

I'm currently developing a Laravel application and facing an issue with the $controller->wantsJson() method in the back-end. This method returns TRUE only if the content type of the request is set to application/json. jQuery.ajax({ type: ...

Unblocking the context menu: How entering JS directly into the address bar compares to using a bookmark

Exploring the concept of blocking the context menu using JavaScript. Here's how you can block such a menu: document.addEventListener('contextmenu', event => event.preventDefault()); I recently came across an article that mentioned this ...