1

I am trying to build a one touch game on HTML5 canvas. It's a running game made with the help of this tutorial:

http://blog.sklambert.com/html5-game-tutorial-game-ui-canvas-vs-dom/

I changed the existing controls from space bar to a mouse click. It works perfectly across all the platforms except Android devices mobile browsers.

In Android devices, the touch makes the user jump. If there is a long hold in the touch, the user keeps jumping even when the touch is released. This problem does not happen in iPhones or iPads or desktops.

Can I make a Javascript function where a mouse down for a certain number of seconds is cut ? Something like:

if(mousedown for 1sec)
    mouseup;

Let me know if you can think of another approach.

Ezequiel Jadib
  • 14,767
  • 2
  • 38
  • 43

1 Answers1

0

You can use touch events rather than mouse for touch enabled devices. Refer: https://developer.mozilla.org/en-US/docs/Web/API/Touch_events/Using_Touch_Events

function is_touch_device() {
  /* Function code taken from http://stackoverflow.com/a/4819886/3946520 */
  return 'ontouchstart' in window        // works on most browsers 
      || navigator.maxTouchPoints;       // works on IE10/11 and Surface
};

if(is_touch_device()) {
    canvas.addEventListener('touchstart', handleTouchStart, false);
    canvas.addEventListener('touchend', handleTouchEnd, false);
}
else {
    // Bind Mouse Events
}

function handleTouchStart(e) {
    // This code runs when user touches the canvas i.e. on touch start
}

function handleTouchEnd(e) {
    // This code runs when user removes finger from canvas i.e. on touch end
}

Also note that there can be scenario where the user puts two or more fingers on the canvas. Each of them will fire 'touchstart' event. So you'll have to handle that. You can refer to http://www.javascriptkit.com/javatutors/touchevents.shtml for a good tutorial on touch events.

kumardeepakr3
  • 395
  • 6
  • 16