Here's a little code snippet for today.
While I was making the 3D CSS Mario Kart, I needed a simple, drop-in bit of code to handle touch interfaces. I looked through some old experiments and found a rough version of the code below. It was based on this KeyboardController by Stack Overflow user Bob Ince.
It doesn't do anything clever. All it does is provide a simple way to attach functionality to touch events in different areas of the screen – top-left, top-center, top-right, middle-left, middle-center, middle-right, bottom-left, bottom-center, bottom-right. My apologies to any Brits for the spelling of centre as 'center'. It's the Internet, we have to.
How to use
Include this code:
function TouchController(areas, repeat) {
var touchtimer;
document.onmousedown = document.ontouchstart = document.ontouchmove = function(e) {
var position;
e.preventDefault();
e.touches = [{'clientX':e.pageX,'clientY':e.pageY}];
switch(true) {
case (e.touches[0].clientY<window.innerHeight/3) :
position = 'top';
break;
case (e.touches[0].clientY>(2*window.innerHeight)/3) :
position = 'bottom';
break;
default :
position = 'middle';
break;
}
position+='-';
switch(true) {
case (e.touches[0].clientX<window.innerWidth/3) :
position += 'left';
break;
case (e.touches[0].clientX>(2*window.innerWidth)/3) :
position += 'right';
break;
default :
position += 'center';
break;
}
if (!(position in areas)) {
return true;
}
areas[position]();
if (repeat!==0) {
clearInterval(touchtimer);
touchtimer= setInterval(areas[position], repeat);
}
return false;
};
// Cancel timeout
document.onmouseup = document.ontouchend= function(e) {
clearInterval(touchtimer);
};
};
Now, all you need to do to attach a function to a touch event in the top-left area of the screen is:
TouchController({
'top-left': function() { topLeftFunction();}
}, 20);
I use this for direction control in the Mario Kart experiment which maps exactly onto the cursor keys used for the normal control.
TouchController({
'top-left': function() { // UP + LEFT
drawMap.move({y: 2});
drawMap.move({z: drawMap.z + 2});
drawMap.sprite(-1)
},
'top-center': function() { // UP
drawMap.move({y: 2});
},
'top-right': function() { // UP + RIGHT
drawMap.move({y: 2});
drawMap.move({z: drawMap.z - 2});
drawMap.sprite(1)
},
'middle-left': function() { // LEFT
drawMap.move({z: drawMap.z + 2});
drawMap.sprite(-1)
},
'middle-right': function() { // RIGHT
drawMap.move({z: drawMap.z - 2});
drawMap.sprite(1)
},
'bottom-left': function() { // DOWN + LEFT
drawMap.move({y: - 2});
drawMap.move({z: drawMap.z + 2});
drawMap.sprite(-1)
},
'bottom-center': function() {
drawMap.move({y: - 2});
},
'bottom-right': function() { // DOWN + RIGHT
drawMap.move({y: - 2});
drawMap.move({z: drawMap.z - 2});
drawMap.sprite(1)
},
}, 20);
If you need anything clever or you need two or more touches, you should use something else. This is just a simple drop-in for when you're copy-paste coding and want to include touch-screen support.