使用缩放将屏幕位置转换为等距瓷砖位置

时间:2013-01-21 13:08:09

标签: c# xna

我正在尝试将鼠标在屏幕上的位置转换为地图上的特定图块。使用下面的功能,我相信我沿着正确的线,但是当我缩放时我无法正确地缩放它。有什么想法吗?

这是我正在使用的功能:

    Vector2 TranslationVectorFromScreen(Vector2 toTranslate)
    {
        Vector2 output = new Vector2();

        toTranslate -= offset; // Offset is the map's offset if the view has been changed

        toTranslate.X /= tileBy2; // tileBy2 is half of the each tile's (sprite) size
        toTranslate.Y /= tileBy4; // tileBy2 is a quarter of the each tile's (sprite) size

        output.X = (toTranslate.X + toTranslate.Y) / 2;
        output.Y = (toTranslate.X - toTranslate.Y) / 2;

        return output;
    }

根据我的调试信息,当我沿着平铺线移动鼠标时,X和Y正在递增,但是它们的值都是错误的,因为没有考虑尺度。我已经尝试在功能中包含刻度以上,但无论我在哪里添加它,它似乎都会让事情变得更糟。作为参考,比例存储为浮点数,其中1.0f表示没有缩放(只是在相关的情况下)。

这是一个屏幕截图,以帮助减轻任何光线:

enter image description here

修改

通过将函数更改为下面的数字,数字似乎仍然在相同的点处递增(即,沿着每个图块的相关轴上升1或下降1),但结果似乎仍然过大。例如,如果结果为100,100,当我放大时,即使鼠标位于同一个图块上,这些也可能会更改为50,50。

新功能:

    Vector2 TranslationVectorFromScreen(Vector2 toTranslate)
    {
        Vector2 output = new Vector2();

        toTranslate -= offset;

        toTranslate.X /= (tileBy2 * scale); // here are the changes
        toTranslate.Y /= (tileBy4 * scale); // 

        output.X = (toTranslate.X + toTranslate.Y) / 2;
        output.Y = (toTranslate.X - toTranslate.Y) / 2;

        return output;
    }

1 个答案:

答案 0 :(得分:1)

在对代码进行了一些处理之后,我似乎找到了解决方案。我会留在这里,以防其他人使用它:

    Vector2 TranslationVectorFromScreen(Vector2 toTranslate)
    {
        Vector2 output = new Vector2();
        Vector2 tempOffset = offset; // copy of the main screen offset as we are going to modify this

        toTranslate.X -= GraphicsDevice.Viewport.Width / 2;
        toTranslate.Y -= GraphicsDevice.Viewport.Height / 2;
        tempOffset.X /= tileBy2;
        tempOffset.Y /= tileBy4;

        toTranslate.X /= tileBy2 * scale;
        toTranslate.Y /= tileBy4 * scale;

        toTranslate -= tempOffset;

        output.X = (toTranslate.X + toTranslate.Y) / 2;
        output.Y = (toTranslate.X - toTranslate.Y) / 2;

        output += new Vector2(-1.5f, 1.5f); // Normaliser - not too sure why this is needed

        output.X = (int)output.X; // rip out the data that we might not need
        output.Y = (int)output.Y; // 

        return output;
    }

我不完全确定为什么标准化器需要在那里,但我总是使用地图的比例和大小,这似乎不会影响这个值所需要的。< / p>

最后,这是一个截图,说明它在左上角工作:

enter image description here

相关问题