首页 > 解决方案 > 如何绘制从现有网格中心偏移的对象?

问题描述

我正在尝试通过更改节点的颜色在已经处于活动状态的瓷砖网格上绘制图像。网格是用双 for 循环绘制的,我有一个适合该区域的图像。目前,图像平铺现有空间,但我希望它居中。

如何使用现有的 for 循环定位图像?

for (int x = 0; x < maxSize; x++)
{
    for (int y = 0; y < maxSize; y++)
    {
        Node tile = new Node();
        tile.x = x;
        tile.z = y;
        // copyImage.GetPixel(y, x) - The image being copied onto the grid 
        tile.currentColor = ColorUtility.ToHtmlStringRGB(Color.white);
        Nodes.Add(tile);
    }
}

标签: c#unity3d

解决方案


经过大量测试,我确实设法解决了这个问题。为了使图像居中而不是平铺,它需要正确的偏移量以及图像限制:

int center = maxSize / 2;
int offsetX = center - copyImage.width / 2;
int offsetY = center - copyImage.height / 2;
int maxY = offsetY + copyImage.height;
int maxX = offsetX + copyImage.width;

for (int x = 0; x < maxSize; x++)
{
    for (int y = 0; y < maxSize; y++)
    {
        Node tile = new Node();
        tile.x = x;
        tile.z = y;

        bool yTrue = y > offsetY && y < maxY;
        bool xTrue = x > offsetX && x < maxX;

        if (yTrue && xTrue)
        {
            tile.currentColor = ColorUtility.ToHtmlStringRGB(copyImage.GetPixel(x - offsetX, y - offsetY));
        } else {
            tile.currentColor = ColorUtility.ToHtmlStringRGB(Color.white);
        }
        tile.currentColor = ColorUtility.ToHtmlStringRGB(Color.white);
        Nodes.Add(tile);
    }
}

推荐阅读