Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

cocos2d-android 開發入門:基礎程式碼與環境配置

編輯:關於 Android 程式設計

本文記錄在 Android 平台上使用 cocos2d-android 建立第一個專案的基礎流程。

1. 建立新專案

首先在開發工具中建立一個新的 Android 專案。

2. 導入 cocos2d-android 函式庫

將下載的 cocos-master 中 cocos2d-android/libs 目錄下的所有檔案複製到專案的 libs 目錄,並將 cocos2d-android.jar 加入 Build Path。

3. 撰寫程式碼

(1)MainActivity:cocos2d 引擎會將圖形渲染到該 view 物件上。

package com.njupt.firstgame;
import org.cocos2d.layers.CCScene;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.opengl.CCGLSurfaceView;
import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity {
    private CCGLSurfaceView view = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = new CCGLSurfaceView(this);
        setContentView(view);
        CCDirector director = CCDirector.sharedDirector();
        director.attachInView(view);        // 設定使用的 view 物件
        director.setDisplayFPS(true);       // 是否顯示 FPS
        director.setAnimationInterval(1.0f/60); // 每幀渲染所需時間
        CCScene scene = CCScene.node();     // 建立遊戲場景
        GameLayer gameLayer = new GameLayer(); // 建立布景層
        scene.addChild(gameLayer);          // 加入布景層至場景
        director.runWithScene(scene);       // 運行場景
    }
}

(2)GameLayer:繼承自 CCLayer 的布景層。

package com.njupt.firstgame;
import org.cocos2d.layers.CCLayer;

public class GameLayer extends CCLayer {
    public GameLayer() {
    }
}

以上就是使用 cocos2d-android 建立專案並跑起第一個場景的基礎程式碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved