Google is committed to advancing racial equity for Black communities. See how.
本頁面由 Cloud Translation API 翻譯而成。
Switch to English

Cocos2d-x

本指南演示瞭如何將AdMob和Firebase包含到新創建的Cocos2d-x項目中。如果您還沒有項目,則可以通過獲取先決條件並從命令行創建新的cocos項目來完成:

cocos new MyGame -l cpp
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID ||
     CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
  ...
#endif

先決條件

您的計算機上必須已安裝以下組件:

  • 最新版本的Cocos2d-x
  • Python 2.7或更高版本
  • NDK r10d或更高版本(僅Android開發需要)
  • CocoaPods 1.0.0或更高版本(僅iOS開發需要)

使用Firebase C ++ SDK獲取AdMob

下載Firebase C ++ SDK 。將文件解壓縮到Cocos2d-x項目的頂級目錄中,該目錄包含proj.android-studioproj.ios_mac目錄。將文件夾命名為firebase_cpp_sdk

設置iOS

以下步驟說明瞭如何將Firebase SDK導入到新創建的Cocos2d-x iOS項目中。

  1. 請按照將Firebase添加到您的應用程序的步驟進行操作。完成後,您在proj.ios_mac/目錄中的Xcode項目應引用GoogleService-Info.plist文件。

  2. proj.ios_mac/目錄中創建具有以下內容的proj.ios_mac/

    source 'https://github.com/CocoaPods/Specs.git'
    
    platform :ios, '7.0'
    
    # Replace "MyGame" with the name of your game.
    target 'MyGame-mobile' do
      pod 'Firebase'
      pod 'Firebase/AdMob'
    end
    
  3. 運行pod update以安裝CocoaPods,並按照MyGame.xcworkspace指示打開MyGame.xcworkspace。目前,您的項目中已包含Firebase和AdMob iOS SDK。

  4. CocoaPods會警告某些屬性缺少$(inherited) 。轉到Xcode中MyGame-mobile目標的構建設置,並為以下每個構建設置在列表底部添加$(inherited)

    • 其他鏈接器標誌
    • 預處理器宏
    • 圖書館搜索路徑
  5. 在構建設置中,將$(PROJECT_DIR)/../firebase_cpp_sdk/frameworks/ios/universal框架搜索路徑 ,將$(PROJECT_DIR)/../firebase_cpp_sdk/include標題搜索路徑

  6. 接下來,您需要包含對要使用的庫的引用。右鍵單擊您的項目,然後選擇將文件添加到“ MyGame” 。從firebase_cpp_sdk/frameworks/ios/universal目錄中,選擇firebase.frameworkfirebase_admob.framework 。在添加框架之前,請取消選中“ 如果需要復制項目”選項。您在上一步中添加的構建設置使Xcode知道在哪裡可以找到框架。

  7. GameController.framework添加到Build Phases> Link Binary with Libraries

  8. 請遵循AdMob的“ 應用程序傳輸安全性”指南,以確保所有廣告在iOS 9及更高版本上均能正常運行。

檢查點:您應該能夠從Xcode構建和運行iOS應用。

現在,您已經設置了集成AdMob和Firebase的iOS項目。您已經準備好設置Android項目。

設定Android

以下步驟說明瞭如何將Firebase SDK導入到新創建的Cocos2d-x Android項目中。

  1. 打開您的proj.android-studio/app/jni/Android.mk並添加下面以粗體顯示的行。確保將FIREBASE_CPP_SDK_DIR設置為剛下載的Firebase C ++ SDK的本地路徑。

    LOCAL_PATH := $(call my-dir)
     
    # The path to the Firebase C++ SDK, in the project's root directory.
    FIREBASE_CPP_SDK_DIR := ../../../firebase_cpp_sdk
     
    APP_ABI := armeabi-v7a x86
    STL := $(firstword $(subst _, ,$(APP_STL)))
    FIREBASE_LIBRARY_PATH := $(FIREBASE_CPP_SDK_DIR)/libs/android/$(TARGET_ARCH_ABI)/$(STL)
     
    include $(CLEAR_VARS)
    LOCAL_MODULE := firebase_app
    LOCAL_SRC_FILES := $(FIREBASE_LIBRARY_PATH)/libapp.a
    LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/$(FIREBASE_CPP_SDK_DIR)/include
    include $(PREBUILT_STATIC_LIBRARY)
     
    include $(CLEAR_VARS)
    LOCAL_MODULE := firebase_feature
    LOCAL_SRC_FILES := $(FIREBASE_LIBRARY_PATH)/libadmob.a
    LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/$(FIREBASE_CPP_SDK_DIR)/include
    include $(PREBUILT_STATIC_LIBRARY)
     
    include $(CLEAR_VARS)
     
    $(call import-add-path,$(LOCAL_PATH)/../../../cocos2d)
    $(call import-add-path,$(LOCAL_PATH)/../../../cocos2d/external)
    $(call import-add-path,$(LOCAL_PATH)/../../../cocos2d/cocos)
    $(call import-add-path,$(LOCAL_PATH)/../../../cocos2d/cocos/audio/include)
     
    LOCAL_MODULE := MyGame_shared
    LOCAL_MODULE_FILENAME := libMyGame
     
    LOCAL_SRC_FILES := hellocpp/main.cpp \
                       ../../../Classes/AppDelegate.cpp \
                       ../../../Classes/HelloWorldScene.cpp
     
    LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../../Classes
     
    # _COCOS_HEADER_ANDROID_BEGIN
    # _COCOS_HEADER_ANDROID_END
     
    LOCAL_STATIC_LIBRARIES := cocos2dx_static
    LOCAL_STATIC_LIBRARIES += firebase_app
    LOCAL_STATIC_LIBRARIES += firebase_feature
     
    # _COCOS_LIB_ANDROID_BEGIN
    # _COCOS_LIB_ANDROID_END
     
    include $(BUILD_SHARED_LIBRARY)
     
    $(call import-module,.)
     
    # _COCOS_LIB_IMPORT_ANDROID_BEGIN
    # _COCOS_LIB_IMPORT_ANDROID_END
    
  2. 檢查您仍然可以編譯您的Cocos應用程序:

    cocos compile -p android --ap android-24 --android-studio --app-abi armeabi-v7a
    
  3. 請按照以下步驟將Firebase添加到位於proj.android-studio/目錄中的應用程序

  4. 在您的app/build.gradle添加廣告包:

    implementation 'com.google.firebase:firebase-ads:19.4.0'
    
  5. 檢查您仍然可以編譯您的Cocos應用程序:

    cocos compile -p android --ap android-42 --android-studio --app-abi armeabi-v7a
    

您的Android項目現在引用了Firebase C ++ SDK中的AdMob組件。

C ++整合

現在,您的iOS和Android項目已在Firebase C ++ SDK中引用,下一步是開始使用SDK並加載一些廣告。

初始化Firebase和AdMob

建議您在應用程序生命週期中儘早初始化Firebase和AdMob。為Cocos2d-x項目添加此初始化代碼的最自然的地方是AppDelegate.cpp文件:

AppDelegate.cpp


#include "firebase/app.h"
#include "firebase/admob.h"

USING_NS_CC;

bool AppDelegate::applicationDidFinishLaunching() {

  ...

  #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
  // Initialize Firebase for Android.
  firebase::App* app = firebase::App::Create(
  firebase::AppOptions(), JniHelper::getEnv(), JniHelper::getActivity());
  // Initialize AdMob.
  firebase::admob::Initialize(*app, "INSERT_YOUR_ADMOB_ANDROID_APP_ID");
  #elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
  // Initialize Firebase for iOS.
  firebase::App* app = firebase::App::Create(firebase::AppOptions());
  // Initialize AdMob.
  firebase::admob::Initialize(*app, "INSERT_YOUR_ADMOB_IOS_APP_ID");
  #endif
  // Initialize AdMob.
  firebase::admob::Initialize(*app);
  // Create a scene. it's an autorelease object.
  auto scene = HelloWorldScene::createScene();
  // run
  director->runWithScene(scene);
  return true;
}

在Android上,創建Firebase應用需要JNI環境和Activity。上面的示例代碼使用Cocos2d-x中的JniHelper類提供這些參數。

找一個廣告家長

AdMob需要firebase::admob::AdParent對象來初始化每種廣告格式。該對像對應於Android上的Activity和iOS上的UIView 。以下幫助程序類創建一個getAdParent()方法,該方法根據平台返回適當的對象。

FirebaseHelper.h

#ifndef __FIREBASE_HELPER_H__
#define __FIREBASE_HELPER_H__

#include "firebase/admob/types.h"

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include <jni.h>
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
extern "C" {
#include <objc/objc.h>
}  // extern "C"
#endif

// Returns a variable that describes the ad parent for the app. On Android
// this will be a JObject pointing to the Activity. On iOS, it's an ID pointing
// to the root view of the view controller.
firebase::admob::AdParent getAdParent();

#endif // __FIREBASE_HELPER_H__

FirebaseHelper.cpp

#include "FirebaseHelper.h"

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "platform/android/jni/JniHelper.h"
#endif

USING_NS_CC;

firebase::admob::AdParent getAdParent() {
  #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
  // Returns the iOS RootViewController's main view (i.e. the EAGLView).
  return (id)Director::getInstance()->getOpenGLView()->getEAGLView();
  #elif (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
  // Returns the Android Activity.
  return JniHelper::getActivity();
  #else
  // A void* for any other environments.
  return 0;
  #endif
}

將此FirebaseHelper類添加到項目的Classes/文件夾中。確保將此文件添加到iOS的Xcode項目中,並在Android.mk(適用於Android)中更新本地源文件:

LOCAL_SRC_FILES := hellocpp/main.cpp \
                   ../../../Classes/AppDelegate.cpp \
                   ../../../Classes/HelloWorldScene.cpp \
                   ../../../Classes/FirebaseHelper.cpp

加載橫幅廣告

下面顯示瞭如何使用上面定義的getAdParent()方法加載橫幅廣告的完整示例。

#include "FirebaseHelper.h"

#include "firebase/admob.h"
#include "firebase/admob/types.h"
#include "firebase/app.h"
#include "firebase/future.h"
#include "firebase/admob/banner_view.h"

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include <android/log.h>
#include <jni.h>
#include "platform/android/jni/JniHelper.h"
#endif

USING_NS_CC;

bool HelloWorld::init()
{
  // General scene setup ...

  #if defined(__ANDROID__)
  // Android ad unit IDs.
  const char* kBannerAdUnit = "ca-app-pub-3940256099942544/6300978111";
  #else
  // iOS ad unit IDs.
  const char* kBannerAdUnit = "ca-app-pub-3940256099942544/2934735716";
  #endif

  // Create and initialize banner view.
  firebase::admob::BannerView* banner_view;
  banner_view = new firebase::admob::BannerView();
  firebase::admob::AdSize ad_size;
  ad_size.ad_size_type = firebase::admob::kAdSizeStandard;
  ad_size.width = 320;
  ad_size.height = 50;
  banner_view->Initialize(getAdParent(), kBannerAdUnit, ad_size);

  // Schedule updates so that the Cocos2d-x update() method gets called.
  this->scheduleUpdate();
  return true;
}

void HelloWorld::update(float delta) {
  // Check that the banner has been initialized.
  if (banner_view->InitializeLastResult().status() ==
      firebase::kFutureStatusComplete) {
    // Check that the banner hasn't started loading.
    if (banner_view->LoadAdLastResult().status() ==
        firebase::kFutureStatusInvalid) {
      // Make the banner visible and load an ad.
      CCLOG("Loading a banner.");
      banner_view->Show();
      firebase::admob::AdRequest my_ad_request = {};
      banner_view->LoadAd(my_ad_request);
    }
  }
}

下一步是什麼

現在,您已經將帶有AdMob SDK的Firebase集成到Cocos2d-x項目中,可以與Google Mobile Ads SDK進行交互並實現您的首選格式: