k0spwn
k0spwn

Reputation: 43

Javascript touch event handle in a game

I'm using a open-source game and I'm trying ( for exercise ) to modify it so it can run on Android. The problem is :

In the original game you use space to jump and I need the game to respond to a tactil event so the charachter can actually jump.

The game use this code to keep track of spacebar events :

var KEY_CODES = {
  32: 'space'
};
var KEY_STATUS = {};
for (var code in KEY_CODES) {
  if (KEY_CODES.hasOwnProperty(code)) {
     KEY_STATUS[KEY_CODES[code]] = false;
  }
}
document.onkeydown = function(e) {
  var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
  if (KEY_CODES[keyCode]) {
    e.preventDefault();
    KEY_STATUS[KEY_CODES[keyCode]] = true;
  }
};
document.onkeyup = function(e) {
  var keyCode = (e.keyCode) ? e.keyCode : e.charCode;
  if (KEY_CODES[keyCode]) {
    e.preventDefault();
    KEY_STATUS[KEY_CODES[keyCode]] = false;
  }
};

// jump higher if the space bar is continually pressed
if (KEY_STATUS.space && jumpCounter) {
  player.dy = player.jumpDy;
}

So how can I transform the touch event in a spacebar event ?

Thanks in advance for helping, I'm new to coding and I'm trying to learn :)

Upvotes: 1

Views: 525

Answers (1)

sdabet
sdabet

Reputation: 18670

You could add the following piece of code to your script, to simulate spacebar events from touch events.

  document.addEventListener("touchstart", function(e) {
    document.onkeydown({ keyCode: 32 });
  });
  document.addEventListener("touchend", function(e) {
    document.onkeyup({ keyCode: 32 });
  });

Upvotes: 1

Related Questions