0

Tạo realtime Multiplayer game sử dụng Google play Game Services trong unity

Trong những bài viết trước đây, tôi đã đề cập nhiều đến việc tạo ra những Multiplayer game trong Unity. Nhưng tất cả những bài viết đó, tôi đã đề cập về việc sử dụng PUN (Photon Unity Networking) hỗ trợ Network interface, Matchmaking. Tình cờ, tôi xem qua một tutorial trên mạng và biết được Google play game services(GPGS) hỗ trợ realtime multiplayer game cho Unity, Android, iOS. Sau đây, tôi xin trình quá trình tạo ra một multiplayer game đơn giản sử dụng GPGS.

Giới thiệu về Google Play Game Services

Là một thư viện thứ 3 (third-party library), hỗ trợ cả turn-based multiplayer và realtime multiplayer game. Ưu điểm:

  • Miễn phí
  • Hỗ trợ Unity
  • Plug-in cũng miễn phí

Thiết lập Google Play Game Services

Vào Google play developer console: tạo 1 game service

Capture01.PNG

Chọn mục "Link apps", tạo ứng dụng cho Android hoặc iOS

Capture02.PNG

Lưu giữ clientID của app để sau thêm vào settings trong Unity, thêm tester để có thể đăng nhập vào ứng dụng qua Google play game services.

Capture03.PNG

Cài đặt Unity Plugin

** Tải plugin tại:** https://github.com/playgameservices/play-games-plugin-for-unity

Import plugin vào Unity

Vào tab window -> chọn GPGS -> Setup -> Android (iOS) nhập clientID app đã lưu

Tạo game demo

Ở trên là các bước thiết lập cho game với plugin GPGS, sau đây tôi sẽ giới thiệu các phần chính của 1 game Multiplayer sử dụng GPGS:

Tạo một lớp **MultiplayerController** quản lý việc giao tiếp giữa các người chơi.

Vì lớp này được sử dụng xuyên suốt trong game với những trường hợp như: matchmaking, player disconnect,... nên nó sẽ là Singleton (chỉ tạo ra 1 instance duy nhất và dễ dàng được sử dụng bởi các lớp khác). Những chức năng chính của lớp này:

  • ** Sign in:**
public void SignInAndStartMPGame() {
    if (! PlayGamesPlatform.Instance.localUser.authenticated) {
        PlayGamesPlatform.Instance.localUser.Authenticate((bool success) => {
            if (success) {
                Debug.Log ("We're signed in! Welcome " + PlayGamesPlatform.Instance.localUser.userName);
                // We could start our game now
            } else {
                Debug.Log ("Oh... we're not signed in.");
            }
        });
    } else {
        Debug.Log ("You're already signed in.");
        // We could also start our game now
    }
}
  • Thiết lập phòng chơi
public void OnRoomSetupProgress (float percent)
{
    ShowMPStatus ("We are " + percent + "% done with setup");
}
  • Đã kết nối với phòng chơi
public void OnRoomConnected (bool success)
{
    if (success) {
        ShowMPStatus ("We are connected to the room! I would probably start our game now.");
    } else {
        ShowMPStatus ("Uh-oh. Encountered some error connecting to the room.");
    }
}

...

  • Nhận message từ người chơi khác
public void OnRealTimeMessageReceived (bool isReliable, string senderId, byte[] data)
{
    ShowMPStatus ("We have received some gameplay messages from participant ID:" + senderId);
}

**Đặc biệt chúng ta chú ý đến phần nhận message từ người chơi, dữ liệu sẽ được truyền dưới dạng byte[]. Chúng ta cần định nghĩa trước độ dài của message trước khi gửi và thứ tự những params gửi, từ đó sau khi nhận message, ta có thể dịch ngược được những dữ liệu.**

Dưới đây là ví dụ:

-** Khi gửi message:**
```Csharp

private byte _protocolVersion = 1;
// Byte + Byte + 2 floats for position
private int _updateMessageLength = 10;
private List<byte> _updateMessage;
public void SendMyUpdate(float posX, float posY) {
    _updateMessage.Clear ();
    _updateMessage.Add (_protocolVersion);
    _updateMessage.Add ((byte)'U');
    _updateMessage.AddRange (System.BitConverter.GetBytes (posX));
    _updateMessage.AddRange (System.BitConverter.GetBytes (posY));
    byte[] messageToSend = _updateMessage.ToArray();
    Debug.Log ("Sending my update message  " + messageToSend + " to all players in the room");
    PlayGamesPlatform.Instance.RealTime.SendMessageToAll (false, messageToSend);
}

-Khi nhận message


byte messageVersion = (byte)data[0];
char messageType = (char)data[1];
if (messageType == 'U' && data.Length == _updateMessageLength) {
    float posX = System.BitConverter.ToSingle(data, 2);
    float posY = System.BitConverter.ToSingle(data, 6);
}

###Kết luận Trên đây, tôi đã giới thiệu Google play game services và những function cơ bản để tạo một multiplayer game, các bạn có thể tham khảo Demo của tôi tại đây:

https://github.com/dzung0709/testArbitBall

References

http://www.raywenderlich.com/category/unity


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí