Thêm tính năng hỗ trợ thao tác chạm

Để xử lý các sự kiện nhập bằng cách chạm, hãy đọc mảng motionEvents trong vòng lặp trò chơi. Các mảng này chứa những sự kiện đã xảy ra kể từ lần xoá mảng gần đây nhất. Số lượng sự kiện nằm trong mảng được lưu trữ tại motionEventsCount.

  1. Lặp lại và xử lý từng sự kiện trong vòng lặp trò chơi. Trong ví dụ này, mã sau đây sẽ lặp lại motionEvents và xử lý các sự kiện đó qua handle_event:

    for(size_t i = 0; i < mApp->motionEventsCount; ++i) {
      GameActivityMotionEvent* motionEvent = mApp->motionEvents[i];
    
      int action = motionEvent->action;
      int actionMasked = action & AMOTION_EVENT_ACTION_MASK;
      int ptrIndex = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >>
        AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
    
      struct CookedEvent ev;
      memset(&ev, 0, sizeof(ev));
    
      if (actionMasked == AMOTION_EVENT_ACTION_DOWN ||
        actionMasked == AMOTION_EVENT_ACTION_POINTER_DOWN) {
          ev.type = COOKED_EVENT_TYPE_POINTER_DOWN;
      } else if (actionMasked == AMOTION_EVENT_ACTION_UP ||
        actionMasked == AMOTION_EVENT_ACTION_POINTER_UP) {
          ev.type = COOKED_EVENT_TYPE_POINTER_UP;
      } else {
          ev.type = COOKED_EVENT_TYPE_POINTER_MOVE;
      }
    
      ev.motionPointerId = motionEvent->pointers[ptrIndex].id;
      ev.motionIsOnScreen = motionEvent->source == AINPUT_SOURCE_TOUCHSCREEN;
      ev.motionX = GameActivityPointerInfo_getX(
        &motionEvent->pointers[ptrIndex]);
      ev.motionY = GameActivityPointerInfo_getY(
        &motionEvent->pointers[ptrIndex]);
    
      if (ev.motionIsOnScreen) {
        // Use screen size as the motion range.
        ev.motionMinX = 0.0f;
        ev.motionMaxX = SceneManager::GetInstance()->GetScreenWidth();
        ev.motionMinY = 0.0f;
        ev.motionMaxY = SceneManager::GetInstance()->GetScreenHeight();
      }
    
      handle_event(&ev);
    }
    
  2. Khi thực hiện xong, nhớ xoá hàng đợi các sự kiện mà bạn vừa xử lý:

    android_app_clear_motion_events(mApp);