有一组带有偏移坐标的图片,计算每张图片在unity中的中心坐标
假设图片的偏移坐标为(offsetX, offsetY) ,偏移坐标为屏幕坐标系,图片长宽为(w, h)
unity的纹理坐标是为0到1的标准坐标系,即图片左下角坐标为(0, 0),图片右上角坐标为(1, 1),这样可知x方向每移动一格像素为1/w,y方向每移动一格像素为1/h。
1、先计算出这组图片整体的中心坐标(centerX, centerY) centerX = (offsetX+w)/2; //遍历找出某张图片offsetX+w最大的再除以2 centerY = (offsetY+h)/2; //遍历找出某张图片offsetY+h最大的再除以2
2、最后计算出每张图片在unity中的中心坐标(cX, cY) cX = 0.5 + (centerX - (offsetX + w / 2)) / w; cY = 0.5 + ((offsetY + h / 2) - centerY ) / h;
class A
{
public:
A(){ }
void initA(int offsetX, int offsetY, int w, int h)
{
m_w = w;
m_h = h;
m_centerX = (double)offsetX + (double)m_w / 2.0;
m_centerY = (double)offsetY + (double)m_h / 2.0;
m_maxW = offsetX + w;
m_maxH = offsetY + h;
}
int m_w;
int m_h;
double m_centerX;
double m_centerY;
int m_maxW;
int m_maxH;
};
void calAllOffset(A* array, int count)
{
double centerX;
double centerY;
centerX = (double)array[0].m_maxW;
centerY = (double)array[0].m_maxH;
for (int i = 1; i < count; i++)
{
if ((double)array[i].m_maxW > centerX)
centerX = (double)array[i].m_maxW;
if ((double)array[i].m_maxH > centerY)
centerY = (double)array[i].m_maxH;
}
centerX *= 0.5;
centerY *= 0.5;
for (int i = 0; i < count; i++)
{
double offsetX = 0.5 + (centerX - array[i].m_centerX) / array[i].m_w;
double offsetY = 0.5 + (array[i].m_centerY - centerY) / array[i].m_h;
std::cout << offsetX << ", " << offsetY << ",\n";
}
}
|