本文說明如何在 C++ 遊戲中使用 Google Play 遊戲服務成就。本文假設您已按照「設定 Google Play 遊戲服務」一文的說明設定專案。您可以在 PgsAchievementsClient 中找到成就 API。
事前準備
建議您先複習成就遊戲概念,這會對您很有幫助。
開始使用成就 API 編寫程式碼之前:
按照「設定 Google Play 遊戲服務」指南的說明安裝並設定應用程式,以便使用 Play 遊戲服務。
按照 Google Play 管理中心指南的說明操作,定義遊戲要解鎖或顯示的成就。
請熟讀「品質檢查清單」中所列的建議。
取得成就用戶端
遊戲必須先取得 PgsAchievementsClient 物件,才能使用成就 API。要取得此物件,您可以呼叫 PgsAchievementsClient_create 方法,然後在活動內傳遞。
解鎖成就
如要解鎖成就,請呼叫 PgsAchievementsClient_unlock 方法,並傳遞 PgsAchievementsClient 和成就 ID。
以下程式碼片段將展示應用程式如何解鎖成就:
// Example Usage void TriggerUnlock(PgsGamesClient* gamesClient) { // You must obtain the achievements client from the main games client PgsAchievementsClient* achievementsClient = PgsGamesClient_getAchievementsClient(gamesClient); // Replace with your actual Achievement ID from the Play Console const char* MY_ACHIEVEMENT_ID = "CgkI...sQw"; UnlockAchievement(achievementsClient, MY_ACHIEVEMENT_ID); }
如果成就是「漸進式」類型 (需要進行多個步驟才能解鎖的成就),請改為呼叫 PgsAchievementsClient_increment。
以下程式碼片段將展示應用程式如何漸進式累計玩家成就:
void IncrementMyAchievement(PgsAchievementsClient* client, const char* achievementId, uint32_t steps) { if (client == nullptr) { return; } // Call the API // Parameters typically include: // 1. Client handle // 2. Achievement ID (string) // 3. Number of steps to increment by (For example, 1) // 4. Callback function // 5. User context (passed to callback) PgsAchievementsClient_increment( client, achievementId, steps, OnIncrementCallback, (void*)achievementId // Pass ID as context so the callback knows which one finished ); } // Example Usage in Game Loop void OnEnemyDefeated(PgsGamesClient* gamesClient) { // Get the achievements client handle PgsAchievementsClient* achievementsClient = PgsGamesClient_getAchievementsClient(gamesClient); // ID from Google Play Console const char* ACH_ENEMY_KILLER = "CgkI...xyz"; // Increment by 1 step IncrementMyAchievement(achievementsClient, ACH_ENEMY_KILLER, 1); }
您不需要另外撰寫解鎖成就的程式碼,只要完成必要的步驟數量後,Google Play 遊戲服務會自動解鎖成就。
建議您在 strings.xml 檔案中定義成就 ID,遊戲就能按照資源 ID 參照成就。發出呼叫來更新及載入成就時,請採用最佳做法,避免超出 API 配額。
顯示成就
如要顯示玩家成就,請呼叫 PgsAchievementsClient_showAchievementsUI。
以下程式碼片段說明應用程式如何顯示預設的成就使用者介面。
void OnShowAchievementsUICallback(void* context, PgsError error) { if (error == PgsError_Success) { // The UI was displayed and closed successfully by the user. // You might resume your game loop here if it was paused. } else { // Handle error (For example,, user not signed in, UI failed to load). } } // Function to trigger the Achievements UI void ShowMyAchievements(PgsAchievementsClient* achievementsClient) { if (achievementsClient == nullptr) { // Log error: Client not initialized return; } // Call the API // Note: The specific arguments often include the client, a callback, and user_data. // Some versions might require the Android Activity or a Request Code as well. PgsAchievementsClient_showAchievementsUI( achievementsClient, OnShowAchievementsUICallback, // Callback function nullptr // Optional user data (context) passed to callback ); }
下圖為預設成就 UI 的範例: