Perfectly Imperfect

I have ever struggling to love myself. I feel the changes that happen during puberty. In my mind, I often feel confused about little things that I’ve never thought about before, about new emotions…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Controller for swiping using pure JavaScript

Photo by Marvin Meyer on Unsplash

There was a time when I tried to make a game involving direction keys using HTML, CSS and JavaScript. Everything went super smoothly until I realized there is no direction key on mobile phones and I was going way too far to change my project content. I looked up online, found a few functions and improved their accuracy by adding some simple calculations in it. In this article, I am using to take you through how to easily implement a controller for touchscreen swiping using pure JS!

Let’s start with an HTML file with jQuery imported. Open the script tag and define several variables to hold the data from the swipes.

I got the data using add event listener with touch start and touch end. Now to reduce error, I need to modify the data a bit and then use if statements to give the result.

Consider the screen as a Cartesian coordinate system, the up and down are y-axis while the left and right are x-axis. Up and right are defined as positive directions. 5 pixel is the number I set to distinguish tap and real swipes.

Then I use absolute values to handle errors for the swipes towards oblique angles. If the swipe’s abs(y) is greater than abs(x), then it is either going up or down. If the swipe’s abs(x) is greater than abs(y), then it is either going left or right.

The rest of them are self-explaining. If up is greater than 0, then the swipe is towards up. Otherwise, it is towards down since up is defined as the positive direction. Same thing for right and left.

That’s it! You can now implement any game with swipe functionality. I really hope this article can help someone!

PS: one quick tip for those who want to test touchscreen swipe functionalities on their non-touchscreen laptops. If you go to Chrome’s inspector and find their toggle device toolbar, they provide touchscreen test mode. Not 100% accurate, but very handy in the early stage testing!

Add a comment

Related posts:

Onboarding New Writers

Thank you for joining ILLUMINATION Integrated Publications supporting more than 15,500 writers on Medium. We apologise for delay to inform you. Some of our editors are unwell. As usual, our workload…

Cravings for life.

It was such a good phase of life when we had cravings for chocolates and noodles in the midnight, life has began to become so complicated with increasing age and is craving for much bigger things in…