Skip to content

Game interaction

The following shows several commonly used interaction methods in games. For a complete set of device interaction related APIs, please seeAPI-Device

Touch events

The most common ways of interaction in games are clicking, dragging, pressing, etc., all of which are related to touch. The Mini Game API provides the most basic touch event monitoring interface:

If you want to achieve more touch-related effects, you need to implement them yourself. The following shows the sample code for implementing clicks and slides:

js
const touchHandler = {
  startX: 0, // Record the starting X coordinate
  startY: 0, // Record the starting X coordinate
  startTime: 0, // Record the start time
  isMoving: false, // Track if the touch is moving
  longPressTimeout: null, // Timer for press and hold
  thresholdDistance: 10, // Threshold distance for movement
  thresholdTime: 300, // Threshold time for tap (milliseconds)
  longPressTime: 500, // Threshold time for press and hold (milliseconds)
  longPressTriggered: false, // Flag to indicate if press and hold was triggered
  onTouchStart: function(event) {
    this.startX = event.touches[0].clientX;
    this.startY = event.touches[0].clientY;
    this.startTime = Date.now(); // Record the start time
    this.isMoving = false; // Reset moving state

    // Set press and hold timer
    this.longPressTimeout = setTimeout(() => {
      this.handleLongPress(event);
    }, this.longPressTime);
  },
  onTouchMove: function(event) {
    this.isMoving = true;
  },
  onTouchEnd: function(event) {
    clearTimeout(this.longPressTimeout);

    const endX = event.changedTouches[0].clientX;
    const endY = event.changedTouches[0].clientY;
    const endTime = Date.now();
    const moveX = endX - this.startX;
    const moveY = endY - this.startY;
    const moveDistance = Math.sqrt(moveX * moveX + moveY * moveY);
    const timeDiff = endTime - this.startTime;

    if (
      timeDiff < this.thresholdTime &&
      moveDistance < this.thresholdDistance
    ) {
      // Handle tap event
      this.handleClick(event);
    } else if (
      this.isMoving &&
      !this.longPressTriggered &&
      moveDistance > this.thresholdDistance
    ) {
      // Handle swipe event
      this.handleSwipe(this.startX, this.startY, endX, endY);
    }

    this.isMoving = false;
    this.longPressTriggered = false;
  },
  onTouchCancel: function(event) {
    clearTimeout(this.longPressTimeout);
    this.isMoving = false;
    this.longPressTriggered = false;
  },
  handleClick: function(event) {
    console.log("Tap", event);
    // Handle tap event here
  },
  handleLongPress: function(event) {
    console.log("Press and hold", event);
    this.longPressTriggered = true;
    // Handle press and hold event here
  },
  handleSwipe: function(startX, startY, endX, endY) {
    const deltaX = endX - startX;
    const deltaY = endY - startY;

    if (Math.abs(deltaX) > Math.abs(deltaY)) {
      // Horizontal swipe
      if (deltaX > 0) {
        console.log("Swipe right");
        // Handle swipe right event here
      } else  {
        console.log("Swipe left");
        // Handle swipe left event here
      }
    } else  {
      // Vertical swipe
      if (deltaY > 0) {
        console.log("Swipe down");
        // Handle swipe down event here
      } else  {
        console.log("Swipe up");
        // Handle swipe up event here
      }
    }
  }
};

wx.onTouchStart(touchHandler.onTouchStart.bind(touchHandler));
wx.onTouchMove(touchHandler.onTouchMove.bind(touchHandler));
wx.onTouchEnd(touchHandler.onTouchEnd.bind(touchHandler));
wx.onTouchCancel(touchHandler.onTouchCancel.bind(touchHandler));

Text input

Sometimes, text input scenarios are used in games, such as logging in to an account, chatting, and other scenarios. The Mini Game API provides the following interfaces for pulling up and monitoring virtual keyboards.

Sample code:

js
wx.onKeyboardConfirm(result => {
  console.warn("User input:", result.value);
...

wx.onTouchStart(result => {
  wx.showKeyboard({
    defaultValue: "",
    maxLength: 100,
    multiple: false,
    confirmHold: false,
    confirmType: "done",
    success: res => {
      console.warn("Keyboard shown successfully", res);
    },
    fail: err,
      console.warn("Failed to show keyboard", err);
    }
  });
});

Device sensors

On mobile devices, sometimes you can do some very special gameplay by monitoring device sensor changes:

  • wx.startDeviceMotionListeningYou can monitor the device orientation, which can be used to implement functions such as panoramic maps.
  • wx.startAccelerometerYou can monitor changes in the accelerometer, which is usually used to measure the acceleration applied to the device, and can be used to implement functions such as gravity sensing.
  • wx.startGyroscopeIt can monitor the changes of the gyroscope, which is usually used to detect the rotation rate of the device in radians per second. It can be used to implement functions such as viewing angle control.
  • wx.startCompassIt can monitor the device orientation (plane), which can be used to implement functions such as compass.

Sample code:

js
const deviceMotionData = { alpha: 0, beta: 0, gamma: 0 };
const accelerometerData = { x: 0, y: 0, z: 0 };
const gyroscopeData = { x: 0, y: 0, z: 0 };
const compassData = { direction: 0, accuracy: 0 };

// Start device motion listening
wx.startDeviceMotionListening({
  success: () => {
    wx.onDeviceMotionChange(res => {
      deviceMotionData = res;
    });
  },
  fail: err => {
    console.error("Failed to start device motion listening:", err);
  }
});

// Start accelerometer
wx.startAccelerometer
  success: () => {
    wx.onAccelerometerChange(res => {
      accelerometerData = res;
    });
  },
  fail: err => {
    console.error("Failed to start accelerometer:", err);
  }
});

// Start gyroscope
wx.startGyroscope
  success: () => {
    wx.onGyroscopeChange(res => {
      gyroscopeData = res;
    });
  },
  fail: err => {
    console.error("Failed to start gyroscope:", err);
  }
});

// Start compass
wx.startCompass
  success: () => {
    wx.onCompassChange(res => {
      compassData = res;
    });
  },
  fail: err => {
    console.error("Failed to start compass:", err);
  }
});