k0spwn
k0spwn

Reputation: 43

Simulate spacebar press with touchevent in javascript/html

I'm trying to port a game on Android and in the game the player press space to jump and I can't find any working solution to simulate a spacebar event when a user touch the screen

Here's the code I've found until now :

/**
 * Keep track of the 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;
  }
};
document.addEventListener("touchstart", function(e) {
  document.onkeydown({ keyCode: 32 });
});
document.addEventListener("touchend", function(e) {
  document.onkeyup({ keyCode: 32 });
});

I don't understand why this doesn't work...

And then this :

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

Above is all the code that use the space bar event

Full Game code

Upvotes: 0

Views: 1208

Answers (2)

afmeva
afmeva

Reputation: 869

you can define a handler and then wrap the jump function. fire it with the event needed. Ex:

function jump(keyEvent) { /* code to jump*/}

this is a bad idea but it can work for you. This way you dont have to worry about the preventDefault method.

function jumpHandler(e) { e.keyCode = 32; jump(e) /*object to simulate the keydown event object*/ }

to avoid the manipulation of event object you could pass an empty function in the same way yo are passing the keyCode property. But you will lose the preventDefault functionality.

function jumpHandler() { jump({keyCode:32, preventDefault: function(){}}) /*object to simulate the keydown event object*/ }

document.addEventListener('touchstart', jumpHandler);
document.onKeydown = jump // here just the reference to the handler

Some times returnig false at the end of function can have the same behavior of preventDefault, I´m telling you this just whether you want to return false instead of calling preventDefault.

:)

Upvotes: 1

Ram Segev
Ram Segev

Reputation: 2571

You need to take the keyCode from the event, try writing ({ e.keyCode: 32});

Upvotes: 1

Related Questions