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

时间:2017-10-25 18:50:25

标签: c++ graphics mouseevent sfml mousepress

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

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

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

此外,我很想听到建议,我可以找到适当的见解和良好解释的例子。提前谢谢。

1 个答案:

答案 0 :(得分:0)

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

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

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

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