Get X and Y offset of sf::View

拈花ヽ惹草 提交于 2019-12-11 07:57:07

问题


How can I get the X and Y offset of sf::View, I'm using sf::View as my 2d camera so when I click the mouse I get the mouse X and Y coords of the tile I'm clicking on

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

This is great, but once I move the camera sf::View the coords, as expected dont take into account the sf::View offset. I dont see any function to get X or Y in the Documentation so I can take into account for the offset. Any help with this would be appreciated.

Thanks.


回答1:


Take a look at sf::RenderTarget::mapPixelToCoords and mapCoordsToPixel. You can use this method to convert coordinates from "view" to "world" space and back. The documentation specifically mentions your needs as an example:

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.

There are also overloaded versions of the methods that take a Vector2i and convert it based on the RenderTarget's view without having to supply the view manually.

If for some reason you can't use (or don't have access to) the RenderTarget, then you can perform the translation manually. It should be quite simple as long as your sf::View does not perform scaling or rotation (that is, it only performs translation).

To get the top left corner of the view, you simply take center and then subtract half of the width and height. Then, you translate your mouse coordinates using the top left corner of the view.

Something like this:

// 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);
}


来源:https://stackoverflow.com/questions/10457812/get-x-and-y-offset-of-sfview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!