语言:C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; namespace MapEditor.Map { /// <summary> /// 2.5D地图坐标转换工具类 /// </summary> public class CoordinateUtil { /// <summary> /// 像素坐标转网格坐标 /// </summary> /// <param name="tileWidth">网格宽度</param> /// <param name="tileHeight">网格高度</param> /// <param name="px">像素x坐标</param> /// <param name="py">像素y坐标</param> /// <returns></returns> public static Point GetCellPoint(int tileWidth, int tileHeight, int px, int py) { int xtile = 0; //网格的x坐标 int ytile = 0; //网格的y坐标 int cx, cy, rx, ry; cx = (int)(px / tileWidth) * tileWidth + tileWidth/2; //计算出当前X所在的以tileWidth为宽的矩形的中心的X坐标 cy = (int)(py / tileHeight) * tileHeight + tileHeight/2;//计算出当前Y所在的以tileHeight为高的矩形的中心的Y坐标 rx = (px - cx) * tileHeight/2; ry = (py - cy) * tileWidth/2; if (Math.Abs(rx)+Math.Abs(ry) <= tileWidth * tileHeight/4)//<=上三角面积 { xtile = (int)(px / tileWidth); ytile = (int)(py / tileHeight) * 2; } else {//偶行 px = px - tileWidth/2; xtile = (int)(px / tileWidth) + 1; py = py - tileHeight/2; ytile = (int)(py / tileHeight) * 2 + 1; } return new Point(xtile - (ytile&1), ytile); } /// <summary> /// 网格坐标转像素坐标 /// </summary> /// <param name="tileWidth">网格宽度</param> /// <param name="tileHeight">网格高度</param> /// <param name="tx">网格x坐标</param> /// <param name="ty">网格y坐标</param> /// <returns></returns> public static Point GetPixelPoint(int tileWidth, int tileHeight, int tx, int ty) { //偶数行tile中心 int tileCenter = (tx * tileWidth) + tileWidth/2; // x象素 如果为奇数行加半个宽 int xPixel = tileCenter + (ty&1) * tileWidth/2; // y象素 int yPixel = (ty + 1) * tileHeight/2; return new Point(xPixel, yPixel); } /// <summary> /// 根据网格索引取得网格坐标 /// </summary> /// <param name="gindex">网格索引</param> /// <param name="cols">网格列数</param> public static Point GetICellPoint( int gindex, int cols ) { int xtile = gindex % cols; int ytile = gindex / cols; return new Point(xtile, ytile); } /// <summary> /// 根据网格索引取得象素坐标 /// </summary> /// <param name="gindex">网格索引</param> /// <param name="cols">网格列数</param> /// <param name="rows">网格行数</param> /// <param name="tileWidth">网格宽度</param> /// <param name="tileHeight">网格高度</param> /// <returns></returns> public static Point GetIPixelPoint( int gindex, int cols, int rows, int tileWidth, int tileHeight ) { Point cellPoint = GetICellPoint(gindex, cols); Point pixelPoint = GetPixelPoint(tileWidth, tileHeight, cellPoint.X, cellPoint.Y); return pixelPoint; } /// <summary> /// 根据网格坐标取得网格索引 /// </summary> /// <param name="gx">网格x坐标</param> /// <param name="gy">网格y坐标</param> /// <param name="cols">网格列数</param> /// <returns></returns> public static int GetCellIndex( int gx, int gy, int cols ) { int gindex = gy * cols + gx; return gindex; } } }