Cocos2D-Android-1之源码详解:22.TileMapTest

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较多

时间: 2024-08-04 00:35:15

Cocos2D-Android-1之源码详解:22.TileMapTest的相关文章

android自定义SlideMenu源码详解之最简单侧滑实现

实现原理:在一个Activity的布局中需要有两部分,一个是菜单(menu)的布局,一个是内容(content)的布局.两个布局横向排列,菜单布局在左,内容布局在右.初始化的时候将菜单布局向左偏移,以至于能够完全隐藏,这样内容布局就会完全显示在Activity中.然后通过监听手指滑动事件,来改变菜单布局的左偏移距离,从而控制菜单布局的显示和隐藏. 下来来实现这个效果: 1.打开layout下的activity_main.xml <LinearLayout xmlns:android="ht

Android编程之Fragment动画加载方法源码详解

上次谈到了Fragment动画加载的异常问题,今天再聊聊它的动画加载loadAnimation的实现源代码: Animation loadAnimation(Fragment fragment, int transit, boolean enter, int transitionStyle) { 接下来具体看一下里面的源码部分,我将一部分一部分的讲解,首先是: Animation animObj = fragment.onCreateAnimation(transit, enter, fragm

Android View 事件分发机制源码详解(View篇)

前言 在Android View 事件分发机制源码详解(ViewGroup篇)一文中,主要对ViewGroup#dispatchTouchEvent的源码做了相应的解析,其中说到在ViewGroup把事件传递给子View的时候,会调用子View的dispatchTouchEvent,这时分两种情况,如果子View也是一个ViewGroup那么再执行同样的流程继续把事件分发下去,即调用ViewGroup#dispatchTouchEvent:如果子View只是单纯的一个View,那么调用的是Vie

Android ArrayMap源码详解

尊重原创,转载请标明出处    http://blog.csdn.net/abcdef314159 分析源码之前先来介绍一下ArrayMap的存储结构,ArrayMap数据的存储不同于HashMap和SparseArray,在上一篇<Android SparseArray源码详解>中我们讲到SparseArray是以纯数组的形式存储的,一个数组存储的是key值一个数组存储的是value值,今天我们分析的ArrayMap和SparseArray有点类似,他也是以纯数组的形式存储,不过不同的是他的

IntentService源码详解

IntentService可以做什么: 如果你有一个任务,分成n个子任务,需要它们按照顺序完成.如果需要放到一个服务中完成,那么IntentService就会使最好的选择. IntentService是什么: IntentService是一个Service(看起来像废话,但是我第一眼看到这个名字,首先注意的是Intent啊.),所以如果自定义一个IntentService的话,一定要在AndroidManifest.xml里面声明. 从上面的"可以做什么"我们大概可以猜测一下Inten

butterknife源码详解

butterknife源码详解 作为Android开发者,大家肯定都知道大名鼎鼎的butterknife.它大大的提高了开发效率,虽然在很早之前就开始使用它了,但是只知道是通过注解的方式实现的,却一直没有仔细的学习下大牛的代码.最近在学习运行时注解,决定今天来系统的分析下butterknife的实现原理. 如果你之前不了解Annotation,那强烈建议你先看注解使用. 废多看图: 从图中可以很直观的看出它的module结构,以及使用示例代码. 它的目录和我们在注解使用这篇文章中介绍的一样,大体

Java concurrent AQS 源码详解

一.引言 AQS(同步阻塞队列)是concurrent包下锁机制实现的基础,相信大家在读完本篇博客后会对AQS框架有一个较为清晰的认识 这篇博客主要针对AbstractQueuedSynchronizer的源码进行分析,大致分为三个部分: 静态内部类Node的解析 重要常量以及字段的解析 重要方法的源码详解. 所有的分析仅基于个人的理解,若有不正之处,请谅解和批评指正,不胜感激!!! 二.Node解析 AQS在内部维护了一个同步阻塞队列,下面简称sync queue,该队列的元素即静态内部类No

深入Java基础(四)--哈希表(1)HashMap应用及源码详解

继续深入Java基础系列.今天是研究下哈希表,毕竟我们很多应用层的查找存储框架都是哈希作为它的根数据结构进行封装的嘛. 本系列: (1)深入Java基础(一)--基本数据类型及其包装类 (2)深入Java基础(二)--字符串家族 (3)深入Java基础(三)–集合(1)集合父类以及父接口源码及理解 (4)深入Java基础(三)–集合(2)ArrayList和其继承树源码解析以及其注意事项 文章结构:(1)哈希概述及HashMap应用:(2)HashMap源码分析:(3)再次总结关键点 一.哈希概

Spring IOC源码详解之容器依赖注入

Spring IOC源码详解之容器依赖注入 上一篇博客中介绍了IOC容器的初始化,通过源码分析大致了解了IOC容器初始化的一些知识,先简单回顾下上篇的内容 载入bean定义文件的过程,这个过程是通过BeanDefinitionReader来完成的,其中通过 loadBeanDefinition()来对定义文件进行解析和根据Spring定义的bean规则进行处理 - 事实上和Spring定义的bean规则相关的处理是在BeanDefinitionParserDelegate中完成的,完成这个处理需

Spring IOC源码详解之容器初始化

Spring IOC源码详解之容器初始化 上篇介绍了Spring IOC的大致体系类图,先来看一段简短的代码,使用IOC比较典型的代码 ClassPathResource res = new ClassPathResource("beans.xml"); DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDe