Sprite Touch Move - RPG Tutorial 9

This post will show you have to implement touch events to make our sprite move.

First off let’s add a touch handler function that will serve as our update() function for mobile touch. Let’s place this function right after our function resize().

function touchHandler(e) {
  var movementRate = 3;
  if(e.touches) {
    e.preventDefault();

    var currentY = e.touches[0].clientY;
    var currentX = e.touches[0].clientX;
    if(currentY > lastY){
      sprite.y += movementRate;
      // alert('down');
    } else if(currentY < lastY) {
      // alert('up');
      sprite.y -= movementRate;
    }

    if(currentX > lastX){
      // alert('right');
       sprite.x += movementRate;
    } else if(currentX < lastX) {
      // alert('left');
      sprite.x -= movementRate;
    }
    lastY = currentY;
    lastX = currentX;
  }
}

Now we need to plug it up with some event listeners. One for touchstart and one for touchmove, see the code block below. Place this right above our touchHandler(). Along with two global variables: lastY & lastX.

document.addEventListener("touchstart", touchHandler);
document.addEventListener("touchmove", touchHandler);
var lastY, lastX;

That should do it! Take a look at the demo below or download the source files for this tutorial that includes everything we’ve reviewed so far!

Demo the thing..

Open Demo

Download Source Files

If you would like the source files for this tutorial: Download source files

Load 0 Comments