TinoArts TinoArts - 7 months ago 15
Javascript Question

Converting Keyboard controls of a javascript game to touch interface

I am currently developing a javascript game, and I can't get touch controls to work on mobile devices. It is a simple game, in which you can press Up arrow to jump, or Down arrow to roll.

I would like to also implement the touch controls, so the touch/hold of the left side of the display would make the character roll, and by touching/holding the right side of the screen, the character jumps.

This is the code that is working for me for the Up and Down arrow:

var KEY_CODES = {
38: 'up',
40: 'down'
};

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;
}
};


And then I can make tha character to do things by doing:

if (KEY_STATUS.up) { stuff and things }


Any advices, hints, recommendations or possible code scraps that might help me? Thanks in advance!

Answer

You should be able to use touch events. In many cases you can use the same functions that you wrote for the keypresses, or you can write them separately. Here's an example

  var touchedElement = document.getElementById("myElementToBeTouched");
  touchedElement.addEventListener("touchstart", funcTouchStart, false);
  touchedElement.addEventListener("touchend", funcTouchEnd, false);
  touchedElement.addEventListener("touchmove", funcTouchMove, false);

  function funcTouchStart(e) {
    //code to do what you want like set variables and check where on screen touch happened

    var touches = e.changedTouches; //gets array of touch points, to get position
  }

  function funcTouchEnd(e) {
    //code
  }

  function funcTouchMove(e) {
    //code
  }

To make them respond to left or right screen, you could use the touches[i].pageX that comes with these events and set the action to happen only if in the 25% of the screen from touches[i].pageX = 0 (for left) or last 25% to where the touches[i].pageX = width of screen/viewport.

This is not a complete working example but I hope its enough to give you an idea of what you could do. If you need more help with these events, try looking at one of MDN examples such as: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Touch_events