【游戏】关于45°角度地图坐标的计算原理

首先贴出代码,下面的代码是将屏幕点击的坐标转换成45°角度地图中的坐标。

 

-(CGPoint) tilePosFromLocation:(CGPoint)location tileMap:(CCTMXTiledMap*)tileMap
{
	// Tilemap position must be subtracted, in case the tilemap position is not at 0,0 due to scrolling
	CGPoint pos = ccpSub(location, tileMap.position);
	
	float halfMapWidth = tileMap.mapSize.width * 0.5f;
	float mapHeight = tileMap.mapSize.height;
	float tileWidth = tileMap.tileSize.width;
	float tileHeight = tileMap.tileSize.height;
	
	CGPoint tilePosDiv = CGPointMake(pos.x / tileWidth, pos.y / tileHeight);
	float inverseTileY = mapHeight - tilePosDiv.y;

	// Cast to int makes sure that result is in whole numbers, tile coordinates will be used as array indices
	float posX = (int)(inverseTileY + tilePosDiv.x - halfMapWidth);
	float posY = (int)(inverseTileY - tilePosDiv.x + halfMapWidth);

	// make sure coordinates are within isomap bounds
	posX = MAX(0, posX);
	posX = MIN(tileMap.mapSize.width - 1, posX);
	posY = MAX(0, posY);
	posY = MIN(tileMap.mapSize.height - 1, posY);
	
	pos = CGPointMake(posX, posY);

	CCLOG(@"touch at (%.0f, %.0f) is at tileCoord (%i, %i)", location.x, location.y, (int)pos.x, (int)pos.y);
	
	return pos;
}

 

先说明一下方法的参数 (CGPoint)location,传递进来的是手指在屏幕上触发的触摸(基于GL坐标系,即原点是左下角)

CGPoint pos = ccpSub(location, tileMap.position);

这个很明显,计算触摸在地图上的坐标(依旧是GL坐标系)

 

CGPoint tilePosDiv = CGPointMake(pos.x / tileWidth, pos.y / tileHeight);

由于瓦片地图的坐标不是以像素为度量单位,而是以块为度量单位,所以这里要根据当前坐标/瓦片像素来获得瓦片地图用的坐标。

 

float inverseTileY = mapHeight - tilePosDiv.y;

瓦片地图的坐标系是以左上角为原点的,所以Y轴不同于GL坐标系。这里语句的作用就是计算出触摸在瓦片地图坐标系的瓦片地图坐标。

 

float posX = (int)(inverseTileY + tilePosDiv.x - halfMapWidth);
float posY = (int)(inverseTileY - tilePosDiv.x + halfMapWidth);

重点来了,这两句很重要,用于将平面坐标转换为斜角坐标。

首先来说说 posX,将 inverseTileY + tilePosDiv.x - halfMapWidth 分成两个部分来看

tilePosDiv.x - halfMapWidth,这是由于从平面坐标旋转为斜角坐标,坐标X比平面坐标有增加(因为X坐标移动到右边了,坐标系坐标往右逐渐增加),斜角地图的X轴移动了整个地图宽度的一半,所以这里就要减去halfMapWidth。

inverseTileY +,这里为什么在X坐标的地方使用Y坐标呢?这是因为平面坐标旋转为斜角坐标时,X坐标由于旋转,其向下有移动,所以这里就要加上Y的坐标。

同理,posY也类似,不同的是平面坐标旋转为斜角坐标时,坐标Y比平面坐标有减少(因为Y坐标移动到左边,坐标系坐标往左逐渐变小),所以这里必须使用减法。

inverseTileY -,自然就是因为Y坐标因为旋转向上移动 ,所以需要减去Y的坐标。

 

【游戏】关于45°角度地图坐标的计算原理_第1张图片

posX = MAX(0, posX);
posX = MIN(tileMap.mapSize.width - 1, posX);
posY = MAX(0, posY);
posY = MIN(tileMap.mapSize.height - 1, posY);

这几句是为了防止坐标超出地图边界设定的。

 

 

转载于:https://www.cnblogs.com/kingime/p/3682039.html

你可能感兴趣的:(【游戏】关于45°角度地图坐标的计算原理)