1 CCTMXTiledMap的使用
TileMap.h
#ifndef __T23TileMap_H__
#define __T23TileMap_H__
#include "cocos2d.h"
USING_NS_CC;
class TileMap :public CCLayer
{
public:
CREATE_FUNC(TileMap);
bool init();
static CCScene * scene();
CCTMXTiledMap* _map;
CCPoint Point2Tile(CCPoint ptGL);
CCPoint Tile2PointLB(CCPoint ptTile);
bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent);
};
#endif
TileMap.cpp
#include "TileMap.h"
CCScene * TileMap::scene()
{
CCScene * scene = CCScene::create();
TileMap * layer = TileMap::create();
scene->addChild(layer);
return scene;
}
bool TileMap::init()
{
CCScene * scene = CCScene::create();
//初始化TMXTiledMap,要用一个.tmx
CCTMXTiledMap * map = CCTMXTiledMap::create("Round1.tmx");
addChild(map);
//获得CCTMXLayer的层:layer_0
CCTMXLayer* layer = map->layerNamed("layer_0");
//通过tileAt的方式获得格子,每个格子是一个精灵
CCSprite* sprite = layer->tileAt(ccp(2,2));
//通过tileGIDAT的方式获得gid的值
int gid = layer->tileGIDAt(ccp(2,2));
//让被选中的精灵跳动一下
sprite->runAction(CCJumpBy::create(200, ccp(0, 0), 50, 1000));
//将地图缩放
map->setScale(.5f);
layer->setTileGID(3,ccp(3,3));
_map = map;
setTouchEnabled(true);
//设置触摸方式
setTouchMode(kCCTouchesOneByOne);
CCSprite* sprite1 = CCSprite::create("anchor3.png");
_map->addChild(sprite1);
sprite1->setZOrder(1000);
sprite1->setPosition(Tile2PointLB(ccp(3, 2)));
sprite1->setAnchorPoint(ccp(0,1));
sprite1->setPosition(Tile2PointLB(ccp(3, 2)));
sprite1->setAnchorPoint(ccp(0,1));
return true;
}
//将世界坐标转换成格子坐标
CCPoint TileMap::Point2Tile(CCPoint ptGL)
{
//获得每个格子的宽度
int dx = _map->getTileSize().width;
//设置每个格子的高度
int dy = _map->getTileSize().height;
//将ptGL世界坐标转换成为本地坐标
CCPoint ptMap = _map->convertToNodeSpace(ptGL);
//x轴方向的格子数
int x = ptMap.x / dx;
//这里如果是最左下角算的的值是0,如果y轴上有2个格子,实际的格子的y是1
int y = ptMap.y / dy;
//y方向上的总格子数 - 1 - y
y = _map->getMapSize().height - 1 - y;
return ccp(x,y);
}
//将格子坐标转换成为世界坐标
CCPoint TileMap::Tile2PointLB(CCPoint ptTile)
{
//这里的getMapSize().height不是像素值,而是y方向上的格子数
ptTile.y = _map->getMapSize().height - 1 - ptTile.y;
return ccp(ptTile.x * _map->getTileSize().width,
ptTile.y * _map->getTileSize().height);
}
bool TileMap::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
//获得被选中的坐标值
CCPoint pt = pTouch->getLocation();
CCPoint ptTile = Point2Tile(pt);
_map->layerNamed("layer_0")->setTileGID(0, ptTile);
return true;
}
运行结果: