Can multiple if statements be executed simultaneously in plain Javascript? If yes, what is the method to do so?

Currently, I'm developing a game using canvas in HTML, CSS, and vanilla JavaScript. I've successfully created two characters with movement controls assigned to player 1 and player 2. However, a challenge arises when waiting for one player to move their character before the other player can input their movements.

Player 1 navigates using the WAD keys while Player 2 uses the arrow keys. The issue lies in the inability to have both players press their respective buttons simultaneously. One character remains stagnant if their key was pressed first while the other character moves. Additionally, executing a combination move such as jumping and moving right at the same time becomes problematic. Currently, the system involves redrawing the characters (squares) to different positions based on the key inputs.

    var canvas;
    var context;
    var framesPerSecond = 30;
    //player1
    var player1X = 110;
    var player1Y = 650;
    var gravity1 = 1;

    //player2
    var player2X = 810;
    var player2Y = 650;
    var gravity2 = 1;

    window.onload = function(){
        canvas = document.getElementById("canvas");
        context = canvas.getContext("2d");
        console.log("Onload Working");

        setInterval(function(){
            drawEverything();
        }, 1000/framesPerSecond);

        document.addEventListener('keydown', function(event){
            MoveEverything(event);
        });
    }

    function drawEverything(){
        //move player 1
        if(player1Y < 450){
            player1Y = 450;
        }
        else if(player1Y < 650){
            player1Y += gravity1;
            gravity1 += 1;
        }
        else if(player1Y === 650){
            player1Y = 650;
            gravity1 = 1;
        }
        //move Player2
        if(player2Y < 450){
            player2Y = 450;
        }
        else if(player2Y < 650){
            player2Y += gravity2;
            gravity2 += 1;
        }
        else if(player2Y === 650){
            player2Y = 650;
            gravity2 = 1;
        }
        colorRect(0, 0, canvas.width, canvas.height, 'white');
        colorRect(0, 690, canvas.width, 10, '#7e7e7e');
        colorRect(player1X, player1Y, 40, 40, '#7F0019');
        colorRect(player2X, player2Y, 40, 40, '#003366');
    }

    function MoveEverything(event){
        var key_press = String.fromCharCode(event.keyCode);
        var key_code = event.keyCode;
        console.log(key_code, key_press);
        //player 1 movement
        if(key_press == "D"){
            player1X += 10; 
        }
        else if(key_press == "A"){
            player1X -= 10;
        }
        else if(key_press == "W"){
            player1Y -= 200;
        }
        else if(key_code == 39){
            player2X += 10;
        }
        else if(key_code == 37){
            player2X -= 10;
        }
        else if(key_code == 38){
            player2Y -= 200;
        }
    }

    function colorRect(leftX, leftY, width, height, color){
        context.fillStyle = color;
        context.fillRect(leftX, leftY, width, height);
    }

I am considering whether executing the 'if statements' simultaneously would resolve this issue. If not, are there alternative solutions that could help overcome this obstacle?

Answer №1

No, JavaScript follows a single-threaded approach and introducing multithreading would not effectively resolve the issue at hand as it may lead to race conditions.

In order to address the problem, consider creating temporary variables for each changing value and applying them after the completion of all the conditional statements.

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

Creating a list of definitions in the form of an HTML table using a multidimensional array in

Currently, I am tackling the following challenge: I must create a public static buildDefinitionList() method that produces an HTML list of definitions (using <dl>, <dt>, and <dd> tags) and then returns the resulting string. If the array c ...

I'm attempting to make a specific element in an array shine in the designated order. What could be causing my code to not function as expected?

Currently, I am working on developing a Simon game. In order to make the divs glow in the sequence of the array used, I have implemented the glowInOrder() function. However, I am facing an issue where only the first div in the array glows, while the rest d ...

Discovering the art of line breaks

Imagine I have a random block of text displayed in a single line, like this: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Due to various reasons such as width settings or text-zoom, the text may display as two or more lines on the viewer&apos ...

Steps to eliminate a horizontal scrollbar

It appears that I am working with CSS 2.1 as the style "overflow-x" is not present in my code. In the snippet below, I have defined headings for a grid and set the Id "pageLength" to introduce a vertical scrollbar for the grid's contents. However, thi ...

Discover the item that offers the inherited characteristic

What is the most effective method to determine the specific parent object of a property when dealing with an object that has multiple prototype parents and a known property name implemented on one of them? For example: var a = { x: 'foo' }; var ...

avoidable constructor in a react component

When it comes to specifying initial state in a class, I've noticed different approaches being used by people. class App extends React.Component { constructor() { super(); this.state = { user: [] } } render() { return <p>Hi</p> ...

rxjs iterates through an array executing each item in sequential order

Is there a way to make observables wait until the previous one has completed when they are created from an array? Any help is appreciated! export class AppComponent{ arr: number[] = [5, 4, 1, 2, 3]; fetchWithObs() { from(this.arr) ...

Using dryscrape for web scraping: encountering an issue when selecting a radio button with CSS

I am attempting to extract data from a dynamically updated table on a webpage using dryscrape. The web page in question is located at . My code functions correctly with tables that are generated when the page is loaded initially. However, I now need to upd ...

Having trouble fixing an ASP Classic Script issue with two unnecessary buttons. The script includes two buttons instead of just one, causing confusion and ineff

Hey there, I've encountered a little issue with the ASP Script and the HTML elements inside the body tags. It seems to be generating two buttons instead of just one, which is not what I intended. My main goal here is to remove one of the buttons so th ...

Guide on incorporating an Angular directive to substitute an element under specific conditions

My goal is to create a directive that replaces an anchor element with a div element under certain conditions. The content of the anchor element should remain unchanged and be included within the new element. The concept involves having an attribute on the ...

Radio buttons have been concealed and are not visible

Tried the solutions recommended in a previous question about radio buttons not showing in Safari and Chrome, but unfortunately, it did not solve my problem. It seems like this issue is different from the one discussed in that question. The WordPress them ...

Encountering difficulties in updating CSS styles using the useState hook in React

I am currently working on creating a modal in react that changes the background color when opened. The goal is to have the background color darken when the modal is activated and return to normal when the modal is closed. I attempted to achieve this using ...

Using Sequelize's association include results in a null value being returned

I am encountering an issue while attempting to link a table in my query using sequelize-cli. Although my query functions correctly, it fails to populate the Adresse table. Only Patient gets populated, while Adresse array is overlooked and returns null. I ...

Struggling to understand the intricacies of utilizing the jQuery index() method within nested parent elements

Can anyone help me figure out how to get the index of a group of elements (specifically the a tags with the class myLink) that are nested within parent elements? I've been trying different methods, but so far I only get a 0 index for the first item an ...

The div placed below a dropdown div when viewed on mobile

I’ve been developing a responsive website that works seamlessly on both mobile and desktop. After some tweaking, I managed to get the navigation menu to display just the way I wanted in desktop mode with no dropdowns. However, an issue arises when switch ...

What is the best way to calculate the cumulative score from the 24 values provided? Should I include an additional SELECT statement or simply sum up the individual scores?

I am trying to generate a query that displays scores for a user across 24 different questions. I have managed to load these scores into a table, but now I want to also include the total score for the same user. Adding a second SELECT statement with SUM() ...

What is the best way to align two square blocks in the center of a page

I am working on a webpage where I need to display the status of two websites - whether they are currently up and running or not. For sites that are up, I want the block to have a light green background, and for those that are down, a light red one. Additio ...

Gain command over the underline style of text without relying on the border property

Ingredients: just a simple text input field. Question: Is there a way to customize the size, color, and position of the underline styling on an input tag? I noticed that the property text-decoration-color is supported in the moz browser engine, but I&apos ...

Error: Unable to register both views with identical name RNDateTimePicker due to Invariant Violation

Encountering an issue while attempting to import: import DropDownPicker from 'react-native-dropdown-picker'; import DateTimePicker from '@react-native-community/datetimepicker'; <DropDownPicker zIndex={5000} ...

Is it possible to seamlessly incorporate a square image into a bootstrap background image slider without having to crop the image?

I've exhausted all the different solutions I've come across on other platforms to resolve this issue, but I'm still unable to find a fix. So here's what I'm struggling with: The problem I'm facing involves finding the correct ...