콘텐츠로 건너뛰기

자주 방문한 페이지

최근 방문한 페이지

navigation

Supporting Multiple Game Controllers

This lesson teaches you to

  1. Map Players to Controller Device IDs
  2. Process Multiple Controller Input

Try it out

Download the sample

ControllerSample.zip

While most games are designed to support a single user per Android device, it's also possible to support multiple users with game controllers that are connected simultaneously on the same Android device.

This lesson covers some basic techniques for handling input in your single device multiplayer game from multiple connected controllers. This includes maintaining a mapping between player avatars and each controller device and processing controller input events appropriately.

Map Players to Controller Device IDs

When a game controller is connected to an Android device, the system assigns it an integer device ID. You can obtain the device IDs for connected game controllers by calling InputDevice.getDeviceIds(), as shown in Verify a Game Controller is Connected. You can then associate each device ID with a player in your game, and process game actions for each player separately.

Note: On devices running Android 4.1 (API level 16) and higher, you can obtain an input device’s descriptor using getDescriptor(), which returns a unique persistent string value for the input device. Unlike a device ID, the descriptor value won't change even if the input device is disconnected, reconnected, or reconfigured.

The code snippet below shows how to use a SparseArray to associate a player's avatar with a specific controller. In this example, the mShips variable stores a collection of Ship objects. A new player avatar is created in-game when a new controller is attached by a user, and removed when its associated controller is removed.

The onInputDeviceAdded() and onInputDeviceRemoved() callback methods are part of the abstraction layer introduced in Supporting Controllers Across Android Versions. By implementing these listener callbacks, your game can identify the game controller's device ID when a controller is added or removed. This detection is compatible with Android 2.3 (API level 9) and higher.

private final SparseArray<Ship> mShips = new SparseArray<Ship>();

@Override
public void onInputDeviceAdded(int deviceId) {
    getShipForID(deviceId);
}

@Override
public void onInputDeviceRemoved(int deviceId) {
    removeShipForID(deviceId);
}

private Ship getShipForID(int shipID) {
    Ship currentShip = mShips.get(shipID);
    if ( null == currentShip ) {
        currentShip = new Ship();
        mShips.append(shipID, currentShip);
    }
    return currentShip;
}

private void removeShipForID(int shipID) {
    mShips.remove(shipID);
}

Process Multiple Controller Input

Your game should execute the following loop to process input from multiple controllers:

  1. Detect whether an input event occurred.
  2. Identify the input source and its device ID.
  3. Based on the action indicated by the input event key code or axis value, update the player avatar associated with that device ID.
  4. Render and update the user interface.

KeyEvent and MotionEvent input events have device IDs associated with them. Your game can take advantage of this to determine which controller the input event came from, and update the player avatar associated with that controller.

The following code snippet shows how you might get a player avatar reference corresponding to a game controller device ID, and update the game based on the user's button press on that controller.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((event.getSource() & InputDevice.SOURCE_GAMEPAD)
                == InputDevice.SOURCE_GAMEPAD) {
        int deviceId = event.getDeviceId();
        if (deviceId != -1) {
            Ship currentShip = getShipForId(deviceId);
            // Based on which key was pressed, update the player avatar
            // (e.g. set the ship headings or fire lasers)
            ...
            return true;
        }
    }
    return super.onKeyDown(keyCode, event);
}

Note: As a best practice, when a user's game controller disconnects, you should pause the game and ask if the user wants to reconnect.

이 사이트는 쿠키를 사용하여 사이트별 언어 및 표시 옵션에 대한 환경설정을 저장합니다.

Google Play에서 성공을 거두는 데 도움이 되는 최신 Android 개발자 뉴스 및 도움말을 받아 보세요.

* 필수 입력란

완료되었습니다.

WeChat에서 Google Developers 팔로우하기

이 사이트를 (으)로 탐색할까요?

페이지를 요청했지만 이 사이트의 언어 환경설정은 입니다.

언어 환경설정을 변경하고 이 사이트를 (으)로 탐색할까요? 언어 환경설정을 나중에 변경하려면 각 페이지 하단의 언어 메뉴를 사용하세요.

이 클래스를 사용하려면 API 수준 이상이 필요합니다.

문서에 대해 선택한 API 수준이 이므로 이 문서가 표시되지 않습니다. 왼쪽 탐색 메뉴의 선택기로 문서 API 수준을 변경할 수 있습니다.

앱에 필요한 API 수준 지정에 관한 자세한 내용은 다양한 플랫폼 버전 지원을 참조하세요.

Take a short survey?
Help us improve the Android developer experience. (April 2018 — Developer Survey)