c++ - 获取 sf::View 的 X 和 Y 偏移量

标签 c++ sfml

我如何获得 sf::View 的 X 和 Y 偏移量,我使用 sf::View 作为我的 2d 相机,所以当我单击鼠标时,我得到了我正在使用的图 block 的鼠标 X 和 Y 坐标点击

void LMButtonDown(int mX, int mY)
{
    printf("[%d][%d]\n", mX / TILE_SIZE, mY / TILE_SIZE);
}

这很好,但是一旦我移动相机 sf::View 坐标,正如预期的那样,不要考虑 sf::View 偏移量。我在 Documentation 中没有看到任何获取 X 或 Y 的函数 所以我可以考虑偏移量。 如有任何帮助,我们将不胜感激。

谢谢。

最佳答案

看看sf::RenderTarget::mapPixelToCoords and mapCoordsToPixel .您可以使用此方法将坐标从“ View ”空间转换为“世界”空间并返回。该文档特别提到您的需求作为示例:

This function finds the 2D position that matches the given pixel of the render-target. In other words, it does the inverse of what the graphics card does, to find the initial position of a rendered pixel.

还有一些重载版本的方法采用 Vector2i 并根据 RenderTarget 的 view 转换它,而无需手动提供 View 。

如果由于某种原因您不能使用(或无权访问)RenderTarget,那么您可以手动执行转换。只要您的 sf::View 不执行缩放或旋转(即,它仅执行平移),它就应该非常简单。

要获得 View 的左上角,只需取中心,然后减去宽度和高度的一半。然后,使用 View 的左上角转换鼠标坐标。

像这样:

// Somewhere else...
sf::View view;

void LMButtonDown(int mX, int mY)
{
    sf::Vector2f viewCenter = view.getCenter();
    sf::Vector2f halfExtents = view.getSize() / 2.0f;
    sf::Vector2f translation = viewCenter - halfExtents;

    mX += static_cast<int>(translation.x);
    mY += static_cast<int>(translation.y);

    printf("[%d][%d]\n", mX / TILE_SIZE, mY / TILE_SIZE);
}

关于c++ - 获取 sf::View 的 X 和 Y 偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10457812/

相关文章:

c++ - 希望定期执行一个函数,但继续执行其余的程序循环

c++ - 毁灭战士 3 来源 : why does a class representing 2-vectors overload the subscript operator twice?

c++ - 将数据从未对齐结构的数组移动到 C++ 中的对齐数组

c++ - 在 Lua 5.2 中使用 'module' 函数?

c++ - SFML RenderWindow 需要很长时间才能打开一个窗口

c++ - 为什么我的按钮类项目共享相同的 lambda 函数?

c++ - 分配给 C++ 类方法?

c++ - 这部分代码是否需要互斥体?

c++ - 运行最基本的 sfml 应用程序时的性能问题

c++ - 如何在(视频)内存中创建缓冲区以使用 OpenGL 进行绘制?