When working on my reverse engineering of 2048 for browsers I wanted it to be playable on mobile devices as well. Problem was, that while you could perfectly use your keyboard to control the tile movement on a desktop, this was not possible on smartphones! Digging through the web I found some partially working solutions but nothing quite good. So I decided to craft it myself and the results work flawlessly!
The ‘start’ variable takes the coordinates of the ‘touchstart’. How do we get those? By adding an event listener to our empty init() function!
Figuring out how to obtain touch positions on mobile turned out to be quite tricky, but in the end I stumbled across this line and it works well.
When the user stops the swipe, we obtain the position of the ‘touchend’ in a similar way:
The end-coordinates are then passed to another function that processes them:
By calculating the absolute values of the coordinates we get the distance travelled while touching on both axes. This is to determine whether the movement was primarily horizontal or vertical. Coordinate origin is the top left corner of the screen, as usual. So if the x-value of touchstart is smaller than that of touchend, it means the user swiped right. Same goes for all other directions.
Detecting swipes is great and all, but what good is it really, if we don’t execute code based on that? For best flexibility we’re going to extend our class to use callbacks:
And some setter functions to initialize them:
In our `process` function we call the callbacks – pun intended – like so:
After we’ve linked the swipe detector file in our index.html, index.php or what have you, we set it up like so:
After initializing we simply add our callback functions and let the fun begin! That’s all there is to it.
Adding detection for swipes to a website can be a great way to improve user interactions, especially in games. It should be used with caution, though, because of ‘reserved inputs’, like swiping down from the top of a page on mobile browsers to refresh it, for example.
For the full script check out the implementation in my project 2048!