What could be causing my JavaScript loop to only display the final value?

Story Behind the Game

In my latest project, I am delving into the world of creating a captivating 2D side-scrolling game using HTML and JavaScript. To ensure smooth gameplay, I have opted to incorporate ES6 for efficient management of all game objects.

Coding Strategy

To keep track of the platforms in each level, I have structured 2 arrays - one for short platforms and another for long platforms.

  • shortPlatform
  • longPlatform

For every platform in the game, there exists a distinct loop responsible for detecting collisions between the player character and the specific platform in question.

However, an issue has surfaced where the loop is only registering collisions with the very last platform.


Outlined below are the snippets of code illustrating the two loops:

                for (let i = 0; i < shortPlatform.length; i++) 
                {
                    shortPlatform[i].renderObject();

                    // check if collide with players
                    var dir = colCheck(player, shortPlatform[i]);
                }

                for (let x = 0; x < longPlatform.length; x++) 
                {
                    longPlatform[x].renderObject();

                    // check if collide with players
                    var dir2 = colCheck(player, longPlatform[x]);
                };

Note of Concern

Despite combing through various suggestions on closures, I am still unable to implement any viable solutions from the existing answers.

Answer №1

The variables dir and dir2 are limited to the scope of your for loops, causing them to be replaced with each iteration. To prevent this, consider using an array to track collisions.

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

Wait for the canvas to fully load before locating the base64 data in HTML5

Wait until the full canvas is loaded before finding the base64 of that canvas, rather than relying on a fixed time interval. function make_base(bg_img, width, height) { return new Promise(function(resolve, reject) { base_image = new Image(); base_imag ...

Route functions cannot be hoisted in the Express framework

Can someone shed light on why my Express routes aren't hoisted? I keep encountering this error: throw new TypeError('Router.use() requires middleware functions'); The error is not present in the following file: var express = requir ...

Display/Conceal content with JQuery on a PHP webpage

I am having trouble with the following code. My intention is to show/hide the content between the #info id when clicking buttons, but nothing seems to be happening. Could you help me identify the issue? echo '<script> $( "#show' . $r ...

Node.js server crashes upon automatic startup but remains stable when started manually

Currently, I am using Node.js and Socket.io to power an online chat feature. To manage the server, I have created a configuration file located at: /etc/init/example.conf The contents of this file are as follows: start on startup exec forever start /var/ ...

API Post request encountering fetch failure

The route "/api/users/register" on my express server allows me to register an account successfully when passing data through Postman. However, when trying to register an account using the front-end React app, I'm encountering a "TYPE ERROR: Failed to ...

Utilizing a function upon page initialization in VueX

I am currently learning Vue with Vuex and I have created a method called 'llamarJson' which is used to retrieve JSON data. However, I am facing difficulties in using this method when the page loads. I have tried various approaches but have not be ...

Is it possible to expand the Angular Material Data Table Header Row to align with the width of the row content?

Issue with Angular Material Data Table Layout Link to relevant feature request on GitHub On this StackBlitz demo, the issue of rows bleeding through the header when scrolling to the right and the row lines not expanding past viewport width is evident. Ho ...

Why Electron is refusing to open a JSON file

Currently, I am attempting to populate filenames using JSON for the onclick='shell.openItem('filename') function. While the console.log(data[i].url) correctly displays the kmz files for each button, I encounter an error when clicking a butto ...

When working on a React/Redux application, how do you decide between explicitly passing down a prop or retrieving it from the global state using mapStateToProps?

As I embark on creating my inaugural React-Redux application, a recurring decision I face is whether to employ <PaginationBox perPage={perPage} /> or opt for <PaginationBox /> and then implement the following logic: function mapStateToProps({p ...

Running a node.js project on the client side without using npm for deployment

Looking for a solution to efficiently deploy my nodejs project with frequent updates. The site does not have npm available, so I have to package the node_modules every time, which results in a large file size (80MB) that takes a long time to send via ftp t ...

How to Determine if Your Chrome Packaged App is Operating in Kiosk Mode

I'm in the process of developing an application that is able to function both in kiosk mode and regular mode (such as opening from a Chrome browser). However, I need certain features to be restricted to kiosk mode only. How can I determine if the appl ...

Guide on exporting type definitions and utilizing them with npm link for a local package

I am in the process of developing a new testing tool called tepper as an alternative to supertest. My goal is to make this package available in both ESM and CJS formats. However, I'm encountering an issue where users of the library are unable to locat ...

What is the best way to ensure a table is responsive while maintaining a fixed header? This would involve the table scrolling when it reaches the maximum viewpoint, while also keeping

Can anyone help me create a responsive table with a fixed header that scrolls when it reaches the maximum viewpoint without scrolling the entire page? I've tried using box-sizing: border-box; and overflow-x:scroll; but it didn't work. Any suggest ...

Utilizing JavaScript to display numerous variables within a text box

After creating an HTML form, I encountered an issue where only one selected item was displayed in the text field. Can anyone help me solve this problem so that multiple names can be printed in the textfield? function myFun(extras) { document.get ...

How can strings of dates be arranged in MM/DD/YYYY order?

Is there a correct way to sort these dates in descending order? I've attempted using arr.sort() and arr.sort().reverse(), searched extensively on stack overflow, but still cannot find a solution. Every attempt at sorting them seems to be incorrect. [ ...

Creating dynamic forms in Vue using v-for

I'm currently experimenting with creating dynamic form fields using v-for and vuex. My approach involves nesting a v-for inside another v-for. The process of adding new form fields works smoothly, but I encountered an issue when attempting to delete t ...

What could be causing my getAsFile() method to return null?

Below is the code I have been working on: document.getElementById("Image_Panel").addEventListener('paste', (event) => { console.log("Initiating image paste - Step 1"); const clipboardData = event.clipboardData; // Checking ...

Webpack configuration for asynchronous loading

I'm having trouble making this work. Can someone please assist? :) (According to the documentation, webpack is capable of handling Promises) Here is what works for me: var compiler = webpack(webpackConfig) However, when I try using a promise, I en ...

Implementing Java script for onkeypress event in a search bar that does not require a button

Currently utilizing this javascript to trigger an event on key press: function myFunction() { if (window.event || window.event.keyCode == 13) { changeSource(); } } function changeSource(){ document.getElementById("frame1").src="Log-In. ...

Tips for accessing private variables

After running this code in nodejs, I noticed that the 'Count' becomes negative for large values of 'count'. It made me wonder, is it the fault of 'count' or 'chain'? What would be the best approach to modify the &apo ...