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?