PlayCanvas + CocoonJS: Touch Events

So, after previously getting the PlayCanvas tutorial running on my mobile using CocoonJS I figured the next step was some interaction with the app.

This video shows a cone pointing in the direction you swipe on the phone:

This is a PlayCanvas app ported through CocoonJS using the same method I detailed in the previous blog post. The PlayCanvas app is located here. You will need to emulate touch events in your browser to interact with it if running on a computer.

Now, the important code parts. To recognize touch events in this way you need to grab the PlayCanvas canvas and add event listeners to it, specifically ‘touchstart’ and ‘touchend’ ones.

I added the code to grab the canvas and add the event listeners into the initialize function of my main PlayCanvas script, like so:

initialize: function () {

    //grab the canvas
    canvas = document.getElementById('application-canvas');
    //add the listeners
    canvas.addEventListener("touchstart", this.onTouchStart, false);
    canvas.addEventListener("touchend", this.onTouchEnd, false);

Now this is added, the function ‘onTouchStart’ will execute every time you start touching the mobile screen, and ‘onTouchEnd’ will execute every time you stop touching the mobile screen. These functions will need to be added to the script like so:

//This function runs when you touch the screen
onTouchStart: function(e){
    firstX = e.touches[0].clientX; //get X position of current touch
    firstY = e.touches[0].clientY; //get Y position of current touch
//This function runs when you stop touching the screen   
onTouchEnd: function(e){
    lastX = e.changedTouches[0].clientX; //get X position of last place touched
    lastY = e.changedTouches[0].clientY; //get Y position of last place touched

Now you have the firstX and firstY which are the locations of where the touch started on the screen, and the lastX and lastY which are the locations of where the touch ended on the screen. Comparing these values you can calculate the length and direction of a swipe on the mobile (if lastX < firstX you can deduce that the user swiped left, for instance).

The full script for this app can be found here on gist.

Twitter: @LizzipFish