I'm using displaying a sf::RenderTexture
in an ImGui::Image
and I'm trying to get the mouse coordinates relative to it.
Here is my code:
if (ImGui::Begin("Viewport", nullptr, GetFlags()))
{
mRenderTexture.clear(mClearColor);
if (!mRenderTexture.create(800, 600))
{
spdlog::error("Failed to create render texture");
return;
}
mView.reset(sf::FloatRect(0, 0, mRenderTexture.getSize().x, mRenderTexture.getSize().y));
mRenderTexture.setView(mView);
auto mousePos = mRenderTexture.mapCoordsToPixel(ImGui::GetMousePos);
spdlog::info("Mouse pos: ({}, {})", mousePos.x, mousePos.y);
mRenderTexture.display();
ImGui::Image(mRenderTexture);
}
I'm trying to get the top-left corner of the viewport to correspond to 0,0 but even if I use the mapCoordsToPixel
function, it still gives the coordinates relative to the window rather than the view that the RenderTexture is using. What do I need to do to convert it to the view coordinates?
I've tried many solutions from SFML forums and it still doesn't work.
You can capture the top-left coordinate of the image in window coordinates by calling
ImVec2 offset = GetCursorPos();
right before you call ImGui::Image(mRenderTexture)
.
If you subtract offset
from sf::Mouse.getPosition(currentWindow)
you should get what you want.