如何使用SFML鼠标移动分别移动多个图像



下面是我的代码,它在窗口中显示两个图像。

现在通过移动鼠标,两个图像一起移动,但我应该如何分别访问它们?

int main()
{
// Let's setup a window
sf::RenderWindow window(sf::VideoMode(640, 480), "SFML ViewTransformation");
// Let's create the background image here, where everything initializes.
sf::Texture BackgroundTexture;
sf::Sprite bd;
sf::Vector2u TextureSize;  //Added to store texture size.
sf::Vector2u WindowSize;   //Added to store window size.
 if(!BackgroundTexture.loadFromFile("bg1.jpg"))
    {
      return -1;
    }
else
{
TextureSize = BackgroundTexture.getSize(); //Get size of texture.
WindowSize = window.getSize();             //Get size of window.
float ScaleX = (float) WindowSize.x / TextureSize.x;
float ScaleY = (float) WindowSize.y / TextureSize.y;     //Calculate scale.
bd.setTexture(BackgroundTexture);
bd.setScale(ScaleX, ScaleY);      //Set scale.
}
// Create something simple to draw
sf::Texture texture;
texture.loadFromFile("background.jpg");
sf::Sprite background(texture);
sf::Vector2f oldPos;
bool moving = false;
sf::View view = window.getDefaultView();
while (window.isOpen()) {
    sf::Event event;
    while (window.pollEvent(event)) {
        switch (event.type) {
            case sf::Event::Closed:
                window.close();
                break;
            case sf::Event::MouseButtonPressed:
                if (event.mouseButton.button == 0) {
                    moving = true;
                    oldPos = window.mapPixelToCoords(sf::Vector2i(event.mouseButton.x, event.mouseButton.y));
                }
                break;
            case  sf::Event::MouseButtonReleased:
                if (event.mouseButton.button == 0) {
                    moving = false;
                }
                break;
            case sf::Event::MouseMoved:
                {
                    if (!moving)
                        break;
                    const sf::Vector2f newPos = window.mapPixelToCoords(sf::Vector2i(event.mouseMove.x, event.mouseMove.y));
                    const sf::Vector2f deltaPos = oldPos - newPos;
                    view.setCenter(view.getCenter() + deltaPos);
                    window.setView(view);

 oldPos = window.mapPixelToCoords(sf::Vector2i(event.mouseMove.x, event.mouseMove.y));
                    break;
                }
 }
    }
    window.clear(sf::Color::White);
    window.draw(bd);
    window.draw(background);
    window.display();
}
}

我也很乐意听到建议,在那里我可以找到具有适当见解和良好解释的示例。提前谢谢。

问题是你移动的是视图而不是精灵本身:

view.setCenter(view.getCenter() + deltaPos);
window.setView(view);

相反,您应该移动精灵。所以用这条线交换上面的两行,它应该可以工作

bd.setPosition(bd.getPosition() - deltaPos);

相关内容

  • 没有找到相关文章

最新更新