JavaScript will only recognize the first two elements of an array when used in an if statement

I have recently rebuilt my game in HTML/CSS/JS from scratch, based on an old question. Everything seems to work fine when there is only one player and one brick present. However, as soon as I introduce multiple bricks, things start to go wrong.

I used an array to store objects and implemented a for-of loop to handle movement within the array. The functionality works by checking if the current element (player) is not the same as the object selected by the loop, and then checks for collisions and logs the results accordingly. Here is the code snippet:

.... // code snippet goes here
.... // CSS code snippet goes here
.... // HTML code snippet goes here

While the code successfully detects collisions with the first brick, it fails to do so with the second brick. This issue seems to stem from the if statement within the move function, but I'm unsure. I have researched extensively, but have not found a solution. Can someone please explain why this behavior is occurring? I prefer to avoid using jQuery, but I am open to using it if necessary.

Answer №1

Upon exiting the move function, you will be returning from the for loop after handling the initial non-currentElement object:

function move(element,direction) {
    let newX=element.x+direction[0];
    let newY=element.y+direction[1];
    for (let Obj of Objects) {
        if (element!==Obj) {
            if (newX>=0&&newY>=0&&(newX+element.width)<=world.width&&(newY+element.height)<=world.height&&(newX>=(Obj.x+Obj.width)||newY>=(Obj.y+Obj.height)||(newX+element.width)<=Obj.x||(newY+element.height)<=Obj.y)) {
                element.x=newX;
                element.y=newY;
                element.setPosition();
                break;
            } else if (newX<=0&&direction[1]==0) {console.log("Off the world to the left")}
            else if (newY<=0&&direction[0]==0) {console.log("Off the world to the bottom")}
            else if ((newX+element.width)>=world.width&&direction[1]==0) {console.log("Off the world to the right")}
            else if ((newY+element.height)>=world.height&&direction[0]==0) {console.log("Off the world to the top")}
            else if (newX<=(Obj.x+Obj.width)) {console.log("Hitting to the right:",Obj)}
            else if (newY<=(Obj.y+Obj.height)) {console.log("Hitting to the top:",Obj)}
            else if ((newX+element.width)>=Obj.x) {console.log("Hitting to the left:",Obj)}
            else if ((newY+element.height)>=Obj.y) {console.log("Hitting to the bottom:",Obj)}

            // It might be more appropriate to simply continue iterating through the Objects array 
            // rather than returning at this point**
            return 1
        }
    }
    return 0;
}

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

Is there a way to use javascript to ensure that CSS variables stick even when overwritten by onclick events?

I have successfully implemented a method to change CSS variables using advice found here. However, I am running into an issue where the changes do not persist. After clicking on a navigation link, the styles momentarily switch to the new values but quickly ...

Guide to embedding bootstrap.min.js into ember-bootstrap extension

I'm currently experiencing an issue with the ember-bootstrap plugin. Following the instructions on their setup page at , I downloaded and installed it. Once I began working on the Navbar, I encountered a problem. The Hamburger menu, which is supposed ...

Retrieving data from a JSON file using JavaScript in a Node.js environment

Seeking help to extract a value from a JSON file in JavaScript but struggling to find the right syntax. If someone could assist me with writing this line of code in Node.js, I would greatly appreciate it. The value I am trying to retrieve is "totalCount". ...

What are some ways to enhance the functionality of the initComplete feature in Dat

$('#example').dataTable( { "initComplete": function(settings, json) { alert( 'DataTables has finished its initialisation.' ); } } ); Is there a way to extend the initComplete function for other languages? $.extend( true, $.f ...

In Javascript, comparing a regular array value with an array value created by the match function

I'm experiencing a problem with comparing values in two different arrays. Here is the code snippet: tagNames = []; tagNames.push('61'); cmt_wrds = '‏‏61'.replace(/[`~!@#$%^&*()_|+\-=?;:&apos ...

The color input click event does not work properly when triggered within a context menu event

This may sound a bit complicated, but let me try to explain it clearly. I'm working on a web app where I want users to be able to change the background color of certain divs. I plan to use a color picker interface for this purpose and utilize the con ...

Utilizing JQuery to extract element tags exclusively, without including their interior content

I am trying to work with a string that includes HTML and I need to remove the span element entirely while preserving its contents within the string (specifically, I want to retain the word "Canadian" and any other elements). var htmlString = <p>Th ...

The process of filtering arrays and utilizing the V-for directive in Vue.js

Utilizing Vue.js, I am attempting to iterate through an array of levels. I successfully received the response json in actions with a forEach function like: let filters = [] const array = response.data array.forEach((element) => ...

Is it possible to save data to a file using React?

As I work on a React web application, the need has arisen to store crucial user data on the client side in a stable manner. Due to the requirement of data stability and the constraint against using Indexed DB, I am considering storing the data as JSON in ...

Troublesome GSP: JavaScript not functioning properly in Gr

I am experiencing an issue with the JavaScript code I have. Here's my code: <script type="text/javascript"><!-- ​$(function () { $('#add').click(function() { $(this).before($('select:eq(0)').clone()); ...

Challenges arise when using ui-select with both multiple selection and asynchronous options

I'm encountering an issue with the ui-select directive (using AngularJS 1.6.4 and Ui-select 0.19.8). You can find my created fiddle here. The dropdown is supposed to display contacts when I type more than 3 characters, without any filtering applied ...

Guide to creating intricate designs on an HTML5 Canvas, one pixel at a time

Imagine a scenario where there is a 900x900 HTML5 Canvas element involved. In this case, there is a function named computeRow, which takes the row number as a parameter and returns an array of 900 numbers. These numbers represent colors ranging from 0 to ...

Utilizing HTML5 Canvas for Shadow Effects with Gradients

Surprisingly, it seems that the canvas API does not support applying gradients to shadows in the way we expect: var grad = ctx.createLinearGradient(fromX, fromY, toX, toY); grad.addColorStop(0, "red"); grad.addColorStop(1, "blue"); ctx.strokeStyle = gra ...

Simplify code by eliminating uuid references

Greetings! I am currently working with some code that is generated within a JSP tag and utilizes the jQuery data function to connect data with a div element. In order to link the jQuery script with the div on the webpage, I have employed a UUID. However, ...

Troubleshooting issue with setting variables in Firefox's JavaScript

I have created a small JavaScript script that defines a value (referred to as stock), which I want to set as the maximum in a dropdown list. It will be set as the maximum value if it exceeds 6. Below is the code snippet: <script type="text/javascript" ...

Vue's reactivity in Vue 3 is exhibiting strange behavior with boolean data

Currently, I am attempting to modify a boolean variable. Upon the initial page load, everything works as expected. However, upon reloading the page, the variable gets updated locally within the method but not in the global data section. As a result, an err ...

Make sure that the parent element is only visible once all of its child elements have

As a newcomer to the world of react, I am facing some challenges. I have created a form in react which includes a dropdown. To ensure reusability across multiple pages, I decided to turn this dropdown into a component that is responsible for fetching all n ...

"multer's single file upload functionality is not functioning properly, but the array upload

Currently, I am facing an issue while using react js to upload a single file. Interestingly, the multer.single() method seems to fail, whereas the multer.array() method works perfectly fine. What could be causing this problem? //Node.js const upload = mult ...

Error: $controller does not function as a controller within another controller

I recently started learning Angular JS and attempted to call one controller within another, but encountered the following error: ionic.bundle.js:21157 TypeError: $controller is not a function at new <anonymous> (http://localhost:8080/itravel/www/js/ ...

Saving a JavaScript array as a Redis list: A step-by-step guide

I'm trying to figure out how to save array values individually in a Redis list instead of saving the whole array as a single value. Any suggestions on how to achieve this? P.S. Please excuse my poor English. var redis = require('redis'), ...