Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Cocos2D-Android-1之源碼詳解:22.TileMapTest

Cocos2D-Android-1之源碼詳解:22.TileMapTest

編輯:關於Android編程

package org.cocos2d.tests;

import java.util.HashMap;

import javax.microedition.khronos.opengles.GL10;

import org.cocos2d.actions.base.CCRepeatForever;
import org.cocos2d.actions.instant.CCCallFuncN;
import org.cocos2d.actions.interval.CCFadeIn;
import org.cocos2d.actions.interval.CCFadeOut;
import org.cocos2d.actions.interval.CCIntervalAction;
import org.cocos2d.actions.interval.CCMoveBy;
import org.cocos2d.actions.interval.CCMoveTo;
import org.cocos2d.actions.interval.CCRotateBy;
import org.cocos2d.actions.interval.CCScaleBy;
import org.cocos2d.actions.interval.CCScaleTo;
import org.cocos2d.actions.interval.CCSequence;
import org.cocos2d.config.ccMacros;
import org.cocos2d.events.CCTouchDispatcher;
import org.cocos2d.layers.CCColorLayer;
import org.cocos2d.layers.CCLayer;
import org.cocos2d.layers.CCScene;
import org.cocos2d.layers.CCTMXLayer;
import org.cocos2d.layers.CCTMXObjectGroup;
import org.cocos2d.layers.CCTMXTiledMap;
import org.cocos2d.menus.CCMenu;
import org.cocos2d.menus.CCMenuItemImage;
import org.cocos2d.nodes.CCDirector;
import org.cocos2d.nodes.CCLabel;
import org.cocos2d.nodes.CCNode;
import org.cocos2d.nodes.CCSprite;
import org.cocos2d.nodes.CCSpriteSheet;
import org.cocos2d.nodes.CCTileMapAtlas;
import org.cocos2d.opengl.CCDrawingPrimitives;
import org.cocos2d.opengl.CCGLSurfaceView;
import org.cocos2d.opengl.CCTextureAtlas;
import org.cocos2d.types.CGPoint;
import org.cocos2d.types.CGSize;
import org.cocos2d.types.ccColor3B;
import org.cocos2d.types.ccColor4B;
import org.cocos2d.types.ccGridSize;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;

public class TileMapTest extends Activity {
    public static final String LOG_TAG = TileMapTest.class.getSimpleName();//得到類的名字,若很多則返回很多
    private CCGLSurfaceView mGLSurfaceView;//創建字段view


    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);//無小標題
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);//全票
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                    WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//不黑

            mGLSurfaceView = new CCGLSurfaceView(this);//實例化view
            setContentView(mGLSurfaceView);//加載view


            // attach the OpenGL view to a window
            CCDirector.sharedDirector().attachInView(mGLSurfaceView);//附加開放圖形語言視圖

            // set landscape mode
            CCDirector.sharedDirector().setLandscape(false);//設置觀景模式

            // show FPS
            CCDirector.sharedDirector().setDisplayFPS(true);

            // frames per second
            CCDirector.sharedDirector().setAnimationInterval(1.0f / 30);

            CCScene scene = CCScene.node();//必要的構造
            scene.addChild(nextAction());//屬於next的子類

            // Make the Scene active
            CCDirector.sharedDirector().runWithScene(scene);
        }
//默認的老3個
    @Override
        public void onStart() {
            super.onStart();
        }

    @Override
        public void onPause() {
            super.onPause();

            CCDirector.sharedDirector().onPause();
        }

    @Override
        public void onResume() {
            super.onResume();

            CCDirector.sharedDirector().onResume();
        }

    @Override
        public void onDestroy() {
            super.onDestroy();

            CCDirector.sharedDirector().end();
        }

    public static final int kTagTileMap = 1;

    static int sceneIdx = -1;
    static Class<?> transitions[] = {//類集合
    TMXIsoZorder.class,
        TMXOrthoZorder.class,
        TMXIsoVertexZ.class,
       // TMXOrthoVertexZ.class,
       TMXOrthoTest.class,
       // TMXOrthoTest2.class,
        TMXOrthoTest3.class,
        TMXOrthoTest4.class,
        TMXIsoTest.class,
        TMXIsoTest1.class,
        TMXIsoTest2.class,
      //  TMXUncompressedTest.class,
        TMXHexTest.class,
       // TMXReadWriteTest.class,
        TMXTilesetTest.class,
        TMXOrthoObjectsTest.class,
        TMXIsoObjectsTest.class,
        TMXTilePropertyTest.class,
        TMXResizeTest.class,
        TMXIsoMoveLayer.class,
        TMXOrthoMoveLayer.class,

        TileMapTest1.class,
        TileMapEditTest.class,
    };

    static CCLayer nextAction() {//3個切換類
        sceneIdx++;
        sceneIdx = sceneIdx % transitions.length;

        return restartAction();
    }

    static CCLayer backAction() {
        sceneIdx--;
        int total = transitions.length;
        if (sceneIdx < 0)
            sceneIdx += total;
        return restartAction();
    }

    static CCLayer restartAction() {
        Class<?> c = transitions[sceneIdx];
        try {
            return (CCLayer) c.newInstance();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }


    static class TileDemo extends  CCLayer {//一個標准的圖層,和其他的相同
        protected CCTextureAtlas atlas;

        public TileDemo() {
            super();

            this.setIsTouchEnabled(true);

            CGSize s = CCDirector.sharedDirector().winSize();

            CCLabel label = CCLabel.makeLabel(title(), "DroidSans", 24);
            addChild(label, 1);
            label.setPosition(s.width/2, s.height-50);

            String subtitle = subtitle();
            if (subtitle != null) {
                CCLabel l = CCLabel.makeLabel(subtitle, "DroidSerif", 14);
                addChild(l, 1);
                l.setPosition(s.width/2, s.height-80);
            }

            CCMenuItemImage item1 = CCMenuItemImage.item("b1.png", "b2.png", this, "backCallback");
            CCMenuItemImage item2 = CCMenuItemImage.item("r1.png", "r2.png", this, "restartCallback");
            CCMenuItemImage item3 = CCMenuItemImage.item("f1.png", "f2.png", this, "nextCallback");

            CCMenu menu = CCMenu.menu(item1, item2, item3);

            menu.setPosition(0, 0);
            item1.setPosition(s.width/2 - 100,30);
            item2.setPosition(s.width/2, 30);
            item3.setPosition(s.width/2 + 100,30);
            addChild(menu, 1);
        }//**********以上不做贅述

        public void registerWithTouchDispatcher() {
            // CCTouchDispatcher.sharedDispatcher().addTargetedDelegate(this, 0, true);
        CCTouchDispatcher.sharedDispatcher().addDelegate(this, 0);
        }

        @Override
        public boolean ccTouchesBegan(MotionEvent event) {
            return true;
        }

        @Override
        public boolean ccTouchesEnded(MotionEvent event) {
return false;
        }

        @Override
        public boolean ccTouchesCancelled(MotionEvent event) {
return false;
        }

        @Override
        public boolean ccTouchesMoved(MotionEvent event) {//觸動按鍵事件
        final int N = event.getHistorySize() - 1;
        if (N <= 0)
        return true;
            CGPoint touchLocation = CGPoint.make(event.getX(), event.getY());//觸動點
            CGPoint prevLocation = CGPoint.make(event.getHistoricalX(N), event.getHistoricalY(N));//歷史點

            touchLocation= CCDirector.sharedDirector().convertToGL(touchLocation);
            prevLocation= CCDirector.sharedDirector().convertToGL(prevLocation);
//轉換2個點的坐標系,從coco2d的坐標到安卓坐標
            CGPoint diff = CGPoint.ccpSub(touchLocation, prevLocation);
//計算點的差距
            CCNode node = getChildByTag(kTagTileMap);//得到節點
            CGPoint currentPos = node.getPosition();//2維坐標系的點
            node.setPosition(CGPoint.ccpAdd(currentPos, diff));//計算新坐標
            return true;
        }

        public void restartCallback(Object sender) {//3個按鈕
            CCScene s = CCScene.node();
            s.addChild(restartAction());
            CCDirector.sharedDirector().replaceScene(s);
        }

        public void nextCallback(Object sender) {
            CCScene s = CCScene.node();
            s.addChild(nextAction());
            CCDirector.sharedDirector().replaceScene(s);
        }

        public void backCallback(Object sender) {
            CCScene s = CCScene.node();
            s.addChild(backAction());
            CCDirector.sharedDirector().replaceScene(s);
        }

        public String title() {
            return "No title";
        }

        public String subtitle() {
            return "drag the screen";
        }//*****以上不做贅述
    }

    static class TileMapTest1 extends TileDemo {//第一個地圖例子

        public TileMapTest1() {
            CCTileMapAtlas map = CCTileMapAtlas.tilemap("tiles.png", "levelmap.tga", 16, 16);//第一個參數可以加載地圖塊,第二個參數加載tga的地圖(這是個舊版的類)
            // Convert it to "alias" (GL_LINEAR filtering)
            map.getTexture().setAliasTexParameters();//用來無縫拼接

            CGSize s = map.getContentSize();//得到map的大小
            String str = String.format("ContentSize: %f, %f", s.width,s.height);//上下文的大小
            ccMacros.CCLOG(LOG_TAG, str);//把那個字符串用log顯示出來

            // If you are not going to use the Map, you can free it now
            // NEW since v0.7
            map.releaseMap();//暫時釋放地圖從內存,當使用的時候系統自行提取

            addChild(map, 0, kTagTileMap);//添加子類

            map.setAnchorPoint(0, 0.5f);//設置錨點

            //id s = [ScaleBy actionWithDuration:4 scale:0.8f];
            //id scaleBack = [s reverse];
            //
            //id seq = [Sequence actions: s,
            //scaleBack,
            //nil];
            //
            //[map runAction:[RepeatForever actionWithAction:seq]];
        }

        public String title() {
            return "TileMapAtlas";
        }

    }

    static class TileMapEditTest extends TileDemo {//又一個demo
        public TileMapEditTest() {
            super();

            CCTileMapAtlas map = CCTileMapAtlas.tilemap("tiles.png", "levelmap.tga", 16, 16);//和上次一樣的地圖

            // Create an Aliased Atlas
            map.getTexture().setAliasTexParameters();//設置無邊模式

            CGSize s = map.getContentSize();//得到地圖大小
            String str = String.format("ContentSize: %f, %f", s.width, s.height);//格式化字符串
            ccMacros.CCLOG(LOG_TAG, str);//輸出字符

            // If you are not going to use the Map, you can free it now
            // [tilemap releaseMap];
            // And if you are going to use, it you can access the data with:
            schedule("updateMap", 0.2f);//執行時間表

            addChild(map, 0, kTagTileMap);//添加子類

            map.setAnchorPoint(0, 0);//設置錨點
            map.setPosition(-20,-200);//設置位置
        }

        public void updateMap(float dt) {
            // IMPORTANT
            //   The only limitation is that you cannot change an empty, or assign an empty tile to a tile
            //   The value 0 not rendered so don't assign or change a tile with value 0

            CCTileMapAtlas tilemap = (CCTileMapAtlas)getChildByTag(kTagTileMap);

            //
            // For example you can iterate over all the tiles
            // using this code, but try to avoid the iteration
            // over all your tiles in every frame. It's very expensive
            //for(int x=0; x < tilemap.tgaInfo->width; x++) {
            //for(int y=0; y < tilemap.tgaInfo->height; y++) {
            //ccColor3B c =[tilemap tileAt:ccg(x,y)];
            //if( c.r != 0 ) {
            //NSLog(@"%d,%d = %d", x,y,c.r);
            //}
            //}
            //}

            // NEW since v0.7
            ccColor3B c = tilemap.tile(ccGridSize.ccg(13,21));//得到13*21的網格的顏色
            c.r++;//r通道+1
            c.r %= 50;//除以50的余數//其實就是從1到50循環
            if( c.r==0)//如果為0
                c.r=1;//則更改為1

            // NEW since v0.7
            tilemap.setTile(c, ccGridSize.ccg(13,21));//設置
        }

        public String title() {
            return "Editable TileMapAtlas";
        }
    }


    static class TMXOrthoTest extends TileDemo {//4
        public TMXOrthoTest() {
            super();

            //
            // Test orthogonal with 3d camera and anti-alias textures
            //
            // it should not flicker. No artifacts should appear
            //

            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("orthogonal-test2.tmx");
//tmx的地圖,創建一個對象
            addChild(map, 0, kTagTileMap);//添加子類

            CGSize s = map.getContentSize();//得到大小
            String str = String.format("ContentSize: %f, %f", s.width,s.height);
//得到字符串
            ccMacros.CCLOG(LOG_TAG, str);//打印log

            for (CCNode child : map.getChildren()) {//foreach循環讓其子類設置反別名地質參數
CCSpriteSheet css = (CCSpriteSheet)child;
                css.getTexture().setAntiAliasTexParameters();
            }

            float [] x = new float[1];
            float [] y = new float[1];
            float [] z = new float[1];
            map.getCamera().getEye(x, y, z);//得到地圖攝像頭的眼
            map.getCamera().setEye(x[0]-200, y[0], z[0]+300);//改變
        }

        public void onEnter() {
            super.onEnter();
            CCDirector.sharedDirector().setProjection(CCDirector.kCCDirectorProjection3D);//創建時進入3d模式
        }

        public void onExit() {
            CCDirector.sharedDirector().setProjection(CCDirector.kCCDirectorProjection2D);//退出時進入2d模式
            super.onExit();
        }


        public String title() {
            return "TMX Orthogonal test";
        }
    }

    static class TMXOrthoTest2 extends TileDemo {//5

        public TMXOrthoTest2() {
            super();
            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("orthogonal-test1.tmx");
            addChild(map, 0, kTagTileMap);//創建並添加地圖

            CGSize s = map.getContentSize();
            ccMacros.CCLOG(LOG_TAG, "ContentSize: " + s.width + "," + s.height);

            for (CCNode node : map.getChildren() ) {//設置平滑地質參數
CCSpriteSheet child =  (CCSpriteSheet)node;
                child.getTexture().setAntiAliasTexParameters();
            }

            map.runAction(CCScaleBy.action(2, 0.5f));//縮放地圖變換
        }

        public String title() {
            return "TMX Ortho test2";
        }
    }

    static class TMXOrthoTest3 extends TileDemo {//6

        public TMXOrthoTest3() {
            super();

            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("orthogonal-test3.tmx");
            addChild(map, 0, kTagTileMap);//創建地圖

            CGSize s = map.getContentSize();
            ccMacros.CCLOG(LOG_TAG, "ContentSize: " + s.width + ", " + s.height);

            for (CCNode node : map.getChildren()) {//設置平滑參數
CCSpriteSheet child = (CCSpriteSheet)node;
                child.getTexture().setAntiAliasTexParameters();
            }
//以上參數介紹之後的地圖重復出現則不在贅述
            map.setScale(0.2f);//設置比例
            map.setAnchorPoint(0.5f, 0.5f);//設置錨點
        }

        public String title() {
            return "TMX anchorPoint test";
        }

    }

    static class TMXOrthoTest4 extends TileDemo {//7

        public TMXOrthoTest4() {
            super();

            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("orthogonal-test4.tmx");
            addChild(map, 0, kTagTileMap);

            CGSize s1 = map.getContentSize();
            ccMacros.CCLOG(LOG_TAG, "ContentSize: " + s1.width + ", " + s1.height);

            for (CCNode node : map.getChildren()) {
CCSpriteSheet child = (CCSpriteSheet)node;
                child.getTexture().setAntiAliasTexParameters();
            }

            map.setAnchorPoint(0, 0);

            CCTMXLayer layer = map.layerNamed("Layer 0");//得到地圖的圖層0
            CGSize s = layer.layerSize;//得到地圖的大小

            CCSprite sprite = null;//創建精靈
            sprite = layer.tileAt(CGPoint.ccp(0,0));//得到圖層中點0.0作為精靈
            sprite.setScale(2);//設置縮放比例2
            sprite = layer.tileAt(CGPoint.ccp(s.width-1,0));//得到x最後一個,y=0的點
            sprite.setScale(2);//也設置為0
            sprite = layer.tileAt(CGPoint.ccp(0,s.height-1));//這個是y的最後一個,x=0
            sprite.setScale(2);//同理
            sprite = layer.tileAt(CGPoint.ccp(s.width-1,s.height-1));
            sprite.setScale(2);

            schedule("removeSprite", 2);//執行移除精靈指令,每2秒
        }

        public void removeSprite(float dt) {
            unschedule("removeSprite");//只執行一次..

            CCTMXTiledMap map = (CCTMXTiledMap) getChildByTag(kTagTileMap);//得到原來的那個地圖
            CCTMXLayer layer = map.layerNamed("Layer 0");//得到圖層0
            CGSize s = layer.layerSize;//得到圖層大小

            CCSprite sprite = layer.tileAt(CGPoint.ccp(s.width-1,0));拿到x最後一個
            layer.removeChild(sprite, true);//刪掉停止動作
        }

        public String title() {
            return "TMX width/height test";//tmx寬高測試
        }

    }

    static class TMXReadWriteTest extends TileDemo {//
        int gid;
        int gid2;

        public TMXReadWriteTest() {
            super();

            gid = 0;//以下同上
            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("orthogonal-test2.tmx");
            addChild(map, 0, kTagTileMap);

            CGSize s = map.getContentSize();
            ccMacros.CCLOG(LOG_TAG, "ContentSize: " + s.width + ", " + s.height);

            CCTMXLayer layer = map.layerNamed("Layer 0");//得到圖層0
            layer.getTexture().setAntiAliasTexParameters();//設置平滑參數

            map.setScale(1);//地圖比例1...等於不縮放,因為怕前面設置過比例影響吧

            CCSprite tile0 = layer.tileAt(CGPoint.ccp(1,63));//得到特殊的某個點
            CCSprite tile1 = layer.tileAt(CGPoint.ccp(2,63));
            CCSprite tile2 = layer.tileAt(CGPoint.ccp(1,62));
            CCSprite tile3 = layer.tileAt(CGPoint.ccp(2,62));
            tile0.setAnchorPoint(0.5f, 0.5f);//設置錨點..動作是以錨點為中心的
            tile1.setAnchorPoint(0.5f, 0.5f);
            tile2.setAnchorPoint(0.5f, 0.5f);
            tile3.setAnchorPoint(0.5f, 0.5f);
//以下是常見的相對移動、相對旋轉、相對放縮、淡出和出現,最後縮放比例回到1
            CCIntervalAction move   = CCMoveBy.action(0.5f, CGPoint.ccp(0,160));
            CCIntervalAction rotate = CCRotateBy.action(2, 360);
            CCIntervalAction scale  = CCScaleBy.action(2, 5);
            CCIntervalAction opacity= CCFadeOut.action(2);
            CCIntervalAction fadein = CCFadeIn.action(2);
            CCIntervalAction scaleback = CCScaleTo.action(1, 1);
            CCCallFuncN finish = CCCallFuncN.action(this, "removeSprite");//得到方法
            CCIntervalAction seq0 = CCSequence.actions(move,
                            rotate, scale, opacity,
                            fadein, scaleback, finish);//動作組合
            CCIntervalAction seq1 = seq0.copy();//拷貝了3份
            CCIntervalAction seq2 = seq0.copy();
            CCIntervalAction seq3 = seq0.copy();

            tile0.runAction(seq0);//開始執行
            tile1.runAction(seq1);
            tile2.runAction(seq2);
            tile3.runAction(seq3);

            gid = layer.tileGIDAt(CGPoint.ccp(0,63));//又得到那個點的gid,應該是該點在圖塊集合中的序號,大於0,如果是0就是沒有,因為title裡0就是空
            ccMacros.CCLOG(LOG_TAG, "Tile GID at:(0,63) is: " + gid);

            schedule("updateCol", 2.0f);//執行這個方法
            schedule("repaintWithGID", 2);
            schedule("removeTiles", 1);

            ccMacros.CCLOG(LOG_TAG, "++++atlas quantity: " + layer.getTextureAtlas().getTotalQuads());
            ccMacros.CCLOG(LOG_TAG, "++++children: " + layer.getChildren().size());

            gid2 = 0;
        }

        public void removeSprite(Object sender) {
            ccMacros.CCLOG(LOG_TAG, "removing tile: " + sender.toString());
            CCTMXLayer p = (CCTMXLayer)((CCNode)sender).getParent();
            p.removeChild((CCNode)sender, true);//刪掉某個節點
            ccMacros.CCLOG(LOG_TAG, "atlas quantity: " + p.getTextureAtlas().getTotalQuads());
        }

        public void updateCol(float dt) {
            CCNode map = getChildByTag(kTagTileMap);//得到地圖
            CCTMXLayer layer = (CCTMXLayer) map.getChildByTag(0);//得到圖層0

            ccMacros.CCLOG(LOG_TAG, "++++atlas quantity: " + layer.getTextureAtlas().getTotalQuads());
            ccMacros.CCLOG(LOG_TAG, "++++children: " + layer.getChildren().size());

            CGSize s = layer.layerSize;
            for( int y=0; y<s.height; y++ ) {
                layer.setTileGID(gid2, CGPoint.ccp(3,y));//改變地圖中的某個瓦片
            }
            gid2 = (gid2 + 1) % 80;
        }

        public void repaintWithGID(float dt) {//重繪gid
            CCNode map = getChildByTag(kTagTileMap);
            CCTMXLayer layer = (CCTMXLayer) map.getChildByTag(0);

            CGSize s = layer.layerSize;
            for( int x=0; x<s.width; x++) {//實現x的循環
                int y = (int) (s.height-1);讓y是最後一行
                int tmpgid = layer.tileGIDAt(CGPoint.ccp(x,y));//循環得到gid
                layer.setTileGID(tmpgid+1, CGPoint.ccp(x,y));//往後畫一行剛才的gid圖,這樣可以多一行y邊框,應該是頂邊框
            }
        }

        public void removeTiles(float dt) {//慣例的方法,
            unschedule("removeTiles");

            CCNode map = getChildByTag(kTagTileMap);
            CCTMXLayer layer = (CCTMXLayer) map.getChildByTag(0);
            CGSize s = layer.layerSize;
            for (int y=0; y<s.height; y++) {
                layer.removeTileAt(CGPoint.ccp(5,y));//刪除x=5的列
            }
        }

        public String title() {
            return "TMX Read/Write test";//地圖讀寫測試
        }
    }

    static class TMXHexTest extends TileDemo {//13

        public TMXHexTest() {
            super();

            CCColorLayer color = CCColorLayer.node(ccColor4B.ccc4(64,64,64,255));
            addChild(color, -1);//顏***層,比圖層0還小在最底下,灰色底面
//同上設定
            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("hexa-test.tmx");//map
            addChild(map, 0, kTagTileMap);

            CGSize s = map.getContentSize();
            ccMacros.CCLOG(LOG_TAG, "ContentSize: " + s.width + "," + s.height);
        }

        public String title() {
            return "TMX Hex test";
        }

    }

    static class TMXIsoTest extends TileDemo {//8

        public TMXIsoTest() {
            super();
//灰階底面
            CCColorLayer color = CCColorLayer.node(ccColor4B.ccc4(64,64,64,255));
            addChild(color, -1);
//創建地圖
            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("iso-test.tmx");
            addChild(map, 0, kTagTileMap);

            // move map to the center of the screen
            CGSize ms = map.getMapSize();//得到地圖大小
            CGSize ts = map.getTileSize();//得到地圖塊大小
            map.runAction(CCMoveTo.action(1.0f,
                            CGPoint.ccp(-ms.width * ts.width/2, -ms.height * ts.height/2)));//給地圖執行動作,向左上移動1/2
        }

        public String title() {
            return "TMX Isometric test 0";
        }

    }

    static class TMXIsoTest1 extends TileDemo {//9
        public TMXIsoTest1() {
            super();
//灰階地板
            CCColorLayer color = CCColorLayer.node(ccColor4B.ccc4(64,64,64,255));
            addChild(color, -1);
//建立地圖
            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("iso-test1.tmx");
            addChild(map, 0, kTagTileMap);

            CGSize s = map.getContentSize();
            ccMacros.CCLOG(LOG_TAG, "ContentSize: " + s.width + "," + s.height);
//設置錨點
            map.setAnchorPoint(0.5f, 0.5f);
        }

        public String title() {
            return "TMX Isometric test + anchorPoint";
        }

    }

    static class TMXIsoTest2 extends TileDemo {//10

        public TMXIsoTest2() {
            super();
//顏***層
            CCColorLayer color = CCColorLayer.node(ccColor4B.ccc4(64,64,64,255));
            addChild(color, -1);
//加載地圖
            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("iso-test2.tmx");
            addChild(map, 0, kTagTileMap);
//得到大小
            CGSize s = map.getContentSize();
            ccMacros.CCLOG(LOG_TAG, "ContentSize: " + s.width + "," + s.height);

            // move map to the center of the screen
            CGSize ms = map.getMapSize();
            CGSize ts = map.getTileSize();
            map.runAction(CCMoveTo.action(1.0f,
                    CGPoint.ccp( -ms.width * ts.width/2, -ms.height * ts.height/2)));//執行動作移動

        }

        public String title() {
            return "TMX Isometric test 2";
        }

    }

    static class TMXUncompressedTest extends TileDemo {//11
        public TMXUncompressedTest() {
            super();
//顏***層
            CCColorLayer color = CCColorLayer.node(ccColor4B.ccc4(64,64,64,255));
            addChild(color, -1);
//加載地圖
            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("iso-test2-uncompressed.tmx");
            addChild(map, 0, kTagTileMap);
//得到地圖大小
            CGSize s = map.getContentSize();
            ccMacros.CCLOG(LOG_TAG, "ContentSize: " + s.width + "," + s.height);

            // move map to the center of the screen
            CGSize ms = map.getMapSize();//地圖型號
            CGSize ts = map.getTileSize();//塊大小
            map.runAction(CCMoveTo.action(1.0f,
                    CGPoint.ccp( -ms.width * ts.width/2, -ms.height * ts.height/2 )));//移動地圖

            // testing release map
            for (CCNode node: map.getChildren()) {
                CCTMXLayer layer = (CCTMXLayer)node;
                layer.releaseMap();//將地圖變為整塊,不知道具體的位子
            }

        }

        public String title() {
            return "TMX Uncompressed test";
        }

    }

    static class TMXTilesetTest extends TileDemo {
        public TMXTilesetTest() {
            super();

            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("orthogonal-test5.tmx");
            addChild(map, 0, kTagTileMap);//加載地圖

            CGSize s = map.getContentSize();
            ccMacros.CCLOG(LOG_TAG, "ContentSize: " + s.width + "," + s.height);

            CCTMXLayer layer = null;
            layer = map.layerNamed("Layer 0");//得到圖層0
            layer.getTexture().setAntiAliasTexParameters();//設置平滑地質

            layer = map.layerNamed("Layer 1");//同理也設置平滑
            layer.getTexture().setAntiAliasTexParameters();

            layer = map.layerNamed("Layer 2");
            layer.getTexture().setAntiAliasTexParameters();
        }

        public String title() {
            return "TMX Tileset test";
        }

    }

    static class TMXOrthoObjectsTest extends TileDemo {
        public TMXOrthoObjectsTest() {
            super();

            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("ortho-objects.tmx");
            addChild(map, -1, kTagTileMap);//得到地圖

            CGSize s = map.getContentSize();
            ccMacros.CCLOG(LOG_TAG, "ContentSize: " + s.width + "," + s.height);
//打字
            ccMacros.CCLOG(LOG_TAG, "----> Iterating over all the group objets");
            CCTMXObjectGroup group = map.objectGroupNamed("Object Group 1");
//根據物體層的名字得到物體層
            for (HashMap<String, String> dict : group.objects) {
                ccMacros.CCLOG(LOG_TAG, "object: " + dict.toString());
            }

            ccMacros.CCLOG(LOG_TAG, "----> Fetching 1 object by name");
            HashMap<String, String> platform = group.objectNamed("platform");
//得到物體層
            ccMacros.CCLOG(LOG_TAG, "platform: " + platform);
        }

        public void draw(GL10 gl) {//給圖像類重寫了方法
            CCTMXTiledMap map = (CCTMXTiledMap) getChildByTag(kTagTileMap);//得到地圖
            CCTMXObjectGroup group = map.objectGroupNamed("Object Group 1");//得到對象組1
            for (HashMap<String, String> dict : group.objects) {//循環
                int x = Integer.parseInt(dict.get("x"));
                int y = Integer.parseInt(dict.get("y"));
                int width = Integer.parseInt(dict.get("width"));
                int height = Integer.parseInt(dict.get("height"));

                gl.glLineWidth(3);//設置畫線的線寬3px

                CCDrawingPrimitives.ccDrawLine(gl, CGPoint.ccp(x,y), CGPoint.ccp(x+width,y) );//畫線
                CCDrawingPrimitives.ccDrawLine(gl, CGPoint.ccp(x+width,y), CGPoint.ccp(x+width,y+height) );//同理
                CCDrawingPrimitives.ccDrawLine(gl, CGPoint.ccp(x+width,y+height), CGPoint.ccp(x,y+height) );
                CCDrawingPrimitives.ccDrawLine(gl, CGPoint.ccp(x,y+height), CGPoint.ccp(x,y) );

                gl.glLineWidth(1);//恢復線寬1px
            }
        }

        public String title() {
            return "TMX Ortho object test";
        }

        public String subtitle() {
            return "You should see a white box around the 3 platforms";
        }

    }

    static class TMXIsoObjectsTest extends TileDemo {

        public TMXIsoObjectsTest() {
            super();
//依然是個地圖
            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("iso-test-objectgroup.tmx");
            addChild(map, -1, kTagTileMap);

            CGSize s = map.getContentSize();
            ccMacros.CCLOG(LOG_TAG, "ContentSize: " + s.width + "," + s.height);

            CCTMXObjectGroup group = map.objectGroupNamed("Object Group 1");
            for (HashMap<String,String> dict : group.objects) {
                ccMacros.CCLOG(LOG_TAG, "object: " + dict);//輸出地圖信息
            }
        }

        public void draw(GL10 gl) {
            CCTMXTiledMap map = (CCTMXTiledMap) getChildByTag(kTagTileMap);
            CCTMXObjectGroup group = map.objectGroupNamed("Object Group 1");//得到對象層1的內容
            for (HashMap<String, String> dict : group.objects) {
                int x = Integer.parseInt(dict.get("x"));
                int y = Integer.parseInt(dict.get("y"));
                int width = Integer.parseInt(dict.get("width"));
                int height =Integer.parseInt(dict.get("height"));

                gl.glLineWidth(3);//改變線寬

                CCDrawingPrimitives.ccDrawLine(gl, CGPoint.ccp(x,y),  CGPoint.ccp(x+width,y) );//劃線
                CCDrawingPrimitives.ccDrawLine(gl, CGPoint.ccp(x+width,y), CGPoint.ccp(x+width,y+height) );
                CCDrawingPrimitives.ccDrawLine(gl, CGPoint.ccp(x+width,y+height), CGPoint.ccp(x,y+height) );
                CCDrawingPrimitives.ccDrawLine(gl, CGPoint.ccp(x,y+height), CGPoint.ccp(x,y) );

                gl.glLineWidth(1);//恢復
            }
        }

        public String title() {
            return "TMX Iso object test";
        }

        public String subtitle() {
            return "You need to parse them manually. See bug #810";
        }

    }

    static class TMXResizeTest extends TileDemo {
        public TMXResizeTest() {
            super();
//地圖
            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("orthogonal-test5.tmx");
            addChild(map, 0, kTagTileMap);

            CGSize s = map.getContentSize();
            ccMacros.CCLOG(LOG_TAG, "ContentSize: " + s.width + "," + s.height);

            CCTMXLayer layer = null;
            layer = map.layerNamed("Layer 0");//得到圖層

            CGSize ls = layer.layerSize;
            for (int y = 0; y < ls.height; y++) {
                for (int x = 0; x < ls.width; x++) {
                    layer.setTileGID(1, CGPoint.ccp( x, y ));//全部置為1
                }
            }
        }

        public String title() {
            return "TMX resize test";
        }

        public String subtitle() {
            return "Should not crash. Testing issue #740";
        }
    }

    static class TMXIsoZorder extends TileDemo {//1
        CCSprite tamara;

        public TMXIsoZorder() {
            super();
//建立地圖
            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("iso-test-zorder.tmx");
            addChild(map, 0, kTagTileMap);

            map.setPosition(-1000,-50);//設置頂點
            CGSize s = map.getContentSize();
            ccMacros.CCLOG(LOG_TAG, "ContentSize: " + s.width + "," + s.height);

            tamara = CCSprite.sprite("grossinis_sister1.png");//創建精靈
            int z = (map.getChildren()!=null?map.getChildren().size():0);//有子類就返回大小沒有就返回0
            map.addChild(tamara, z);//把精靈添加進去
            int mapWidth = (int) (map.getMapSize().width * map.getTileSize().width);
            tamara.setPosition( mapWidth/2, 0);//精靈放中間
            tamara.setAnchorPoint(0.5f, 0);//錨點放精靈0.5f,0

            CCMoveBy move = CCMoveBy.action(10, CGPoint.ccp(300,250));//移動
            CCMoveBy back = move.reverse();//返回
            CCSequence seq = CCSequence.actions(move, back);//來回的動作
            tamara.runAction(CCRepeatForever.action(seq));//永久執行

            schedule("repositionSprite");//時間表執行下面的方法
        }

        public void repositionSprite(float dt) {//方法
            CGPoint p = tamara.getPosition();//得到點
            CCNode map = getChildByTag(kTagTileMap);//得到地圖

            // there are only 4 layers. (grass and 3 trees layers)
            // if tamara < 48, z=4
            // if tamara < 96, z=3
            // if tamara < 144,z=2
//說明一個塊高4*48,我們現在就是要計算在不在上1/4處
            int newZ = (int) (4 - (p.y / 48));//看4-層數是幾
            newZ = (newZ > 0 ? newZ : 0);//看比4-層數大嗎

            map.reorderChild(tamara, newZ);//重新排列子類
        }

        public String title() {
            return "TMX Iso Zorder";
        }

        public String subtitle() {
            return "Sprite should hide behind the trees";
        }

    }


    static class TMXOrthoZorder extends TileDemo {//又一個
        CCSprite tamara;

        public TMXOrthoZorder() {
            super();
//同理得到一個地圖
            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("orthogonal-test-zorder.tmx");
            addChild(map, 0, kTagTileMap);
//得到大小
            CGSize s = map.getContentSize();
            ccMacros.CCLOG(LOG_TAG, "ContentSize: " + s.width + "," + s.height);
//得到精靈
            tamara = CCSprite.sprite("grossinis_sister1.png");
            map.addChild(tamara, map.getChildren().size());
            tamara.setAnchorPoint(0.5f,0);
//設置動作
            CCMoveBy move = CCMoveBy.action(10, CGPoint.ccp(400,450));
            CCMoveBy back = move.reverse();
            CCSequence seq = CCSequence.actions(move, back);
            tamara.runAction(CCRepeatForever.action(seq));
//執行動作
            schedule("repositionSprite");//執行時間表
        }

        public void repositionSprite(float dt) {
            CGPoint p = tamara.getPosition();
            CCNode map = getChildByTag(kTagTileMap);//得到節點

            // there are only 4 layers. (grass and 3 trees layers)
            // if tamara < 81, z=4
            // if tamara < 162, z=3
            // if tamara < 243,z=2

            // -10: customization for this particular sample
            int newZ = (int) (4 - ( (p.y-10) / 81));//設置新的排序
            newZ = Math.max(newZ, 0);//和0取大,不能在底面以下

            map.reorderChild(tamara, newZ);//重排列
        }

        public String title() {
            return "TMX Ortho Zorder";
        }

        public String subtitle() {
            return "Sprite should hide behind the trees";
        }

    }

    static class TMXIsoVertexZ extends TileDemo {//2
        CCSprite tamara;

        public TMXIsoVertexZ() {
            super();
//同理,同上
            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("iso-test-vertexz.tmx");
            addChild(map, 0, kTagTileMap);

            map.setPosition(-700,-50);
            CGSize s = map.getContentSize();
            ccMacros.CCLOG(LOG_TAG, "ContentSize: " + s.width + "," + s.height);

            // because I'm lazy, I'm reusing a tile as an sprite, but since this method uses vertexZ, you
            // can use any CCSprite and it will work OK.
            CCTMXLayer layer = map.layerNamed("Trees");//得到叫樹的圖層
            tamara = layer.tileAt(CGPoint.ccp(29,29));//得到29,29塊

            CCMoveBy move = CCMoveBy.action(10, CGPoint.ccp(300,250));
            CCMoveBy back = move.reverse();
            CCSequence seq = CCSequence.actions(move, back);//移動迂回
            tamara.runAction(CCRepeatForever.action(seq));//執行

            schedule("repositionSprite");//方法
        }

        public void repositionSprite(float dt) {
            // tile height is 64x32
            // map size: 30x30
            CGPoint p = tamara.getPosition();//得到點
            tamara.setVertexZ(-( (p.y+32) /16));//設置精靈的z坐標值,換算到世界坐標比較大小,zorder是局部的,這個是相對所有的,相當於相對所有
        }

        public void onEnter() {
            super.onEnter();

            // TIP: 2d projection should be used
            CCDirector.sharedDirector().setProjection(CCDirector.kCCDirectorProjection2D);
        }

        public void onExit() {
            // At exit use any other projection.
            //[[CCDirector sharedDirector] setProjection:kCCDirectorProjection3D];
            super.onExit();
        }

        public String title() {
            return "TMX Iso VertexZ";
        }

        public String subtitle() {
            return "Sprite should hide behind the trees";
        }

    }

    static class TMXOrthoVertexZ extends TileDemo {//3又一個
        CCSprite tamara;

        public TMXOrthoVertexZ() {
            super();
//建圖過程
            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("orthogonal-test-vertexz.tmx");
            addChild(map, 0, kTagTileMap);

            CGSize s = map.getContentSize();
            ccMacros.CCLOG(LOG_TAG, "ContentSize: " + s.width + "," + s.height);

            // because I'm lazy, I'm reusing a tile as an sprite, but since this method uses vertexZ, you
            // can use any CCSprite and it will work OK.
            CCTMXLayer layer = map.layerNamed("trees");
            tamara = layer.tileAt(CGPoint.ccp(0,11));
//動作發生
            CCMoveBy move = CCMoveBy.action(10, CGPoint.ccp(400,450));
            CCMoveBy back = move.reverse();
            CCSequence seq = CCSequence.actions(move, back);
            tamara.runAction(CCRepeatForever.action(seq));

            schedule("repositionSprite");//時間表發生
        }

        public void repositionSprite(float dt) {
            // tile height is 101x81
            // map size: 12x12
            CGPoint p = tamara.getPosition();
            tamara.setVertexZ( -( (p.y+81) /81) );//和上文一樣
        }

        public void onEnter() {
            super.onEnter();

            // TIP: 2d projection should be used
            CCDirector.sharedDirector().setProjection(CCDirector.kCCDirectorProjection2D);//設置為2d投影
        }

        public void onExit() {
            // At exit use any other projection.
            //[[CCDirector sharedDirector] setProjection:kCCDirectorProjection3D];
            super.onExit();
        }

        public String title() {
            return "TMX Ortho vertexZ";
        }

        public String subtitle() {
            return "Sprite should hide behind the trees";
        }
    }

    static class TMXIsoMoveLayer extends TileDemo {//移動的
        public TMXIsoMoveLayer() {
            super();

            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("iso-test-movelayer.tmx");
            addChild(map, 0, kTagTileMap);
//見圖
            map.setPosition(-700,-50);

            CGSize s = map.getContentSize();
            ccMacros.CCLOG(LOG_TAG, "ContentSize: " + s.width + "," + s.height);
        }

        public String title() {
            return "TMX Iso Move Layer";
        }

        public String subtitle() {
            return "Trees should be horizontally aligned";
        }

    }

    static class TMXOrthoMoveLayer extends TileDemo {
        public TMXOrthoMoveLayer() {
            super();

            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("orthogonal-test-movelayer.tmx");//見地圖
            addChild(map, 0, kTagTileMap);

            CGSize s = map.getContentSize();
            ccMacros.CCLOG(LOG_TAG, "ContentSize: " + s.width + "," + s.height);
        }//輸出大小

        public String title() {
            return "TMX Ortho Move Layer";
        }

        public String subtitle() {
            return "Trees should be horizontally aligned";
        }

    }

    static class TMXTilePropertyTest extends TileDemo {
        public TMXTilePropertyTest() {
            super();
            CCTMXTiledMap map = CCTMXTiledMap.tiledMap("ortho-tile-property.tmx");
            addChild(map, 0, kTagTileMap);//建地圖

            for (int i=1;i<=20;i++){//輸出gid
                ccMacros.CCLOG(LOG_TAG, "GID:" + i + ", Properties:" + map.propertiesForGID(i));
            }
        }

        public String title() {
            return "TMX Tile Property Test";
        }

        public String subtitle() {
            return "In the console you should see tile properties";
        }

    }


}
//各種地圖建立方法:
//CCTileMapAtlas map = CCTileMapAtlas.tilemap("tiles.png", "levelmap.tga", 16, 16);
//CCTMXTiledMap map = CCTMXTiledMap.tiledMap("orthogonal-test2.tmx");
//tmx較多

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved