Touch the Target: A Simple JavaScript Touch Event Game


Touch events are events that are triggered when a user interacts with a touch-enabled device, such as a smartphone or a tablet. These events allow you to capture touch gestures, such as tapping, swiping, and dragging, and use them to build interactive web applications or games.

Here's a step-by-step guide to create a simple touch-based game using JavaScript:

Step 1: Set up HTML Markup

First, you'll need to set up the HTML markup for your game. For example, you can create a simple game container with a canvas element where you'll draw the game graphics. You can also create any additional HTML elements, such as buttons or score displays, that you'll need for your game.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="icon" type="image/ico" href="logo.png" />
    <title>Document</title>
    <style>
      @import url("https://fonts.googleapis.com/css2?family=Lobster&family=Poppins:wght@100;200;300;400;500;600;700;800&display=swap");
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: "Poppins", sans-serif;
      }
      h3 {
        font-weight: 600;
        text-transform: uppercase;
      }
      #game {
        width: 400px;
        height: 200px;
        background-color: #ddd;
        position: relative;
      }
      #ball {
        width: 25px;
        height: 25px;
        background-color: red;
        border-radius: 25px;
        position: absolute;
        top: 75px;
        left: 75px;
      }
    </style>
  </head>
  <body>
    <h3>Simple Ball Game</h3>
    <div id="game">
      <div id="ball"></div>
    </div>
    <script src="touch.js"></script>
  </body>
</html>

Step 2: Set up JavaScript File

Next, you'll need to create a JavaScript file (e.g., "touch.js") that will contain the game logic. In this file, you can define variables to store game state, such as the player's score or the game objects' positions. You can also set up an event listener for touch events.

Step 3: Handle Touch Events

In the event listener functions, you can access information about the touch events, such as the position of the touch on the screen. You can use this information to update your game state, such as moving game objects or detecting collisions.

touch.js

const game = document.getElementById("game");
const ball = document.getElementById("ball");
let startX, startY;

game.addEventListener("touchstart", function (e) {
  const touch = e.changedTouches[0];
  startX = touch.clientX;
  startY = touch.clientY;
});

game.addEventListener("touchmove", function (e) {
  const touch = e.changedTouches[0];
  const diffX = touch.clientX - startX;
  const diffY = touch.clientY - startY;
  ball.style.left = Math.max(0, Math.min(350, ball.offsetLeft + diffX)) + "px";
  ball.style.top = Math.max(0, Math.min(180, ball.offsetTop + diffY)) + "px";
  startX = touch.clientX;
  startY = touch.clientY;
  e.preventDefault();
});
Live Preview

This code sets up touch event listeners for a simple game where a ball can be moved around within a container element with id "game". Let's go through it step by step:

  1. The touchstart event listener is set up on the "game" element. When a touch event starts (i.e., a user touches the screen), the event handler function is triggered.
  2. Inside the touchstart event handler function, the changedTouches property of the event object is used to get information about the first touch point (in this case, e.changedTouches[0]). The clientX and clientY properties of the touch point represent the initial touch coordinates, which are stored in startX and startY variables for later use.
  3. The touchmove event listener is set up on the "game" element as well. When a touch event moves (i.e., a user moves their finger on the screen), the event handler function is triggered.
  4. Inside the touchmove event handler function, the changedTouches property of the event object is used again to get information about the touch point that has moved. The clientX and clientY properties of the touch point represent the current touch coordinates.
  5. The difference between the current touch coordinates and the initial touch coordinates (diffX and diffY) is calculated to determine how much the ball should be moved horizontally and vertically.
  6. The style.left and style.top properties of the "ball" element are updated to change its position on the screen. The Math.max and Math.min functions are used to limit the ball's position within the boundaries of the "game" element, so that it doesn't move outside of the visible area.
  7. The startX and startY variables are updated with the current touch coordinates, so that they can be used as the initial touch coordinates in the next touchmove event.
  8. Finally, e.preventDefault() is called to prevent any default behavior of touch events, such as scrolling or zooming, to ensure smooth handling of the game's touch controls.

Note: The "ball" element is assumed to exist in the HTML markup and has an initial position set using CSS. The code provided only handles the touch events for moving the ball and does not include any game logic or additional features.

List of Programs


JS Practical Questions & Answers


JS Practical Project