Jump to content

JQuery game - Make two players move at the same time

robeng

Hi! I have a projekt where we need to create a game with JQuery. Two players play at the same time with the same keyboard. But, the problem is that you only can move one character at a time. If i press the left arrow key and the D only one of the caracter moves.

 

Here is my project!
JSfiddle : https://jsfiddle.net/5jsbLnwp/1/
Thanks in advance!

Link to comment
Share on other sites

Link to post
Share on other sites

It seems that one key stroke stops another key stroke from repeating, instead of depending on key repeat, create yourself an keyboard object that will remember if key is pressed down, and then you can check for a key if it is pressed or not. Something like:

 

var keyboard = {};

window.addEventListener('keydown', function(e){
  keyboard[e.keyCode] = true;
});

window.addEventListener('keyup', function(e){
  keyboard[e.keyCode] = false;
});

So there is one handler for each event, it is unnecessary to create one handler for each player. Then you can just check if arrow up is clicked by:

if(keyboard[38]){
	//...
}

Another thing is depending on animations, I would ditch that idea, and would try to create game loop for logic, so changing players positions, and maybe another loop for updating DOM elements position using requestAnimationFrame. But you can try doing that in just one loop.

 

You can try to go oop style, or help yourself a little by just doing simple player objects:

var player1 = {
  x: 0,
  y: 0,
  element: document.getElementById('player1')
};
var player2 = /* similar for player2 */;

function gameLoop(){
  if(keyboard[39]){ //If arrow right key is hold
    player1.x++;
    player1.element.style.left = player1.x;
  }
  
  if(keyboard[68]){ //If d key is hold
    player2.x++;
    player2.element.style.left = player1.x;
  }
}

setInterval(function(){gameLoop();}, 1000 / 60);

I don't know if jQuery is your requirement, but it easy to change it to jQuery.

 

P.S.: I wouldn't use any weird characters inside variable names like ö in spelareHöjd, but it just me, and it may work just fine.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×