1.普通视图获取对应位置图素
CCTMXLayer *layer=map->layerNamed("Layer 0");
CCSize s=layer->getLayerSize();
CCPoint touchPoint=touch->getLocationInView();
touchPoint=CCDirector::sharedDirector()->convertToGL(touchPoint);
int indexx=(touchPoint.x)/map->getTileSize().width;
int indexy=map->getMapSize().height-(touchPoint.y)/map->getTileSize().height;
sprite=layer->tileAt(ccp(indexx,indexy));
sprite->setScale(2);
//map->getMapSize().height 获取图片的长宽像素个数
//getTileSize().height 获取一个图素的高度与宽度
总体思路就是具体位置除以图素的宽高,但这里需要注意,在Y轴的处理上略有不同。因为Cocos2D-X中的坐标系中,Y轴是从下到上一次增加的,而地图中的行数则是从上到下增加的,这就需要做一个转换,用总的函数减去Y轴坐标除以图素高,结果才是所有图素的函数。
2.45度角视图获取对应图素
CCPoint HelloWorld::converttto2d(float x,float y)
{
CCTMXTiledMap *map=(CCTMXTiledMap *)getChildByTag(1);
int mapWidth=map->getMapSize().width*map->getTileSize().width;
int mapHeight=map->getMapSize().height*map->getTileSize().height;
double distanse,sin1,sin11,sin22,cos11,cos1;
int d2x,d2y;
double mystatic5=sqrt(5.0);
double mystatic=16*mystatic5;
if (x>mapWidth/2)
{
distanse=sqrt((x-mapWidth/2)*(x-mapWidth/2)+(mapHeight-y)*(mapHeight-y));
sin1=(mapHeight-y)/distanse;
cos1=(x-mapWidth/2)/distanse;
sin11=(sin1*2-cos1)/mystatic5;
cos11=(sin1+cos1*2)/mystatic5;
d2y=distanse*5/4*sin11/mystatic;
sin22=(2*sin1+cos1)/mystatic5;
d2x=distanse*5/4*sin22/mystatic;
return ccp(d2x.d2y);
}
else
{
distanse=sqrt((mapWidth/2-x)*(mapWidth/2-x)+(mapHeight-y)*(mapHeight-y));
sin1=(mapHeight-y)/distanse;
cos1=(mapWidth/2-x)/distanse;
sin11=(sin1*2-cos1)/mystatic5;
cos11=(sin1+cos1*2)/mystatic5;
d2x=distanse*5/4*sin11/mystatic;
sin22=(2*sin1+cos1)/mystatic5;
d2y=distanse*5/4*sin22/mystatic;
return ccp(d2x,d2y);
}
}