【游戲】關於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的坐標。

 

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

這幾句是為了防止坐標超出地圖邊界設定的。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM