Knowing what to do now becomes quite straightforward. The only wrinkle is that we don't just check for positives and negatives, otherwise we'd be
detecting minor finger wobbles rather than proper swipes. Instead, we specify the positives have to be
quite positive, and the negatives have to be
quite negative.
function MyTouchEndHandler(MyEvent) {
var rect = myCanvas.getBoundingClientRect();
var Touch_End_x = MyEvent.changedTouches[0].clientX - rect.left;
var Touch_End_y = MyEvent.changedTouches[0].clientY - rect.top;
var x_diff = Touch_End_x- Touch_Start_x;
var y_diff = Touch_End_y - Touch_Start_y;
if (x_diff < -100) {tennis.velocity_x = tennis.velocity_x - 10}; // Swipe Left
if (x_diff > 100) {tennis.velocity_x = tennis.velocity_x + 10}; // Swipe Right
if (y_diff > 100) {tennis.velocity_y = tennis.velocity_y + 10}; // Swipe Down
if (y_diff < -100) {tennis.velocity_y = tennis.velocity_y - 10}; // Swipe Up
MyEvent.preventDefault()
}
We've taken a few shortcuts in this swipe-detection. Proper swipe-detection not only checks the finger travelled enough in a given direction, but also that it happened in a short enough period of time, and that it didn't stray in any other directions. A proper implementation would also handle multiple fingers, whereas we're only considering a single finger. But it works well enough for our purposes.