在SFML事件中发送鼠标位置

时间:2012-11-06 22:19:51

标签: c++ sfml

我一直在研究正确的语法,将mouseX和mouseY位置传递给我的班级。

我的尝试是这样的:

 // Start the game loop
 while (window.isOpen())
 {
     // Process events
     sf::Event event;
     while (window.pollEvent(event))
     {
         // Close window : exit
         if (event.type == sf::Event::Closed) {
             window.close();
         }
     }

     // Clear screen
     window.clear();

     // Draw the sprite
     window.draw(sprite);
     window.draw(lsprite);

     if(btn_quit.IsIn(sf::Event::MouseMoveEvent::x,sf::Event::MouseMoveEvent::y){
         btn_quit.RenderImg(window,"button_on.png");
     } else {
         btn_quit.RenderImg(window,"button.png");
     }
  ///rest of the code not relevant to this issue

这是我班上的:

bool IsIn( int mouseX, int mouseY )
{
    if (((mouseX > m_x) && (mouseX < m_x + m_w)) 
    && ((mouseY > m_y) && (mouseY < m_y + m_h ) ) ) {
        return true;
    } else {
        return false;
    }
}

我一直在输入x和y的错误,但是怎么说:

error C2597: illegal reference to non-static member 'sf::Event::MouseMoveEvent::x'

error C2597: illegal reference to non-static member 'sf::Event::MouseMoveEvent::y'

2 个答案:

答案 0 :(得分:3)

您正试图静态访问结构的非静态成员字段。你不能这样做。尝试这样的事情:

// Start the game loop
while (window.isOpen())
{
    // Process events
    sf::Event event;
    while (window.pollEvent(event))
    {
        // Close window : exit
        if (event.type == sf::Event::Closed) {
            window.close();
        }
        else if (event.type == sf::Event::MouseMove)
        {
            if(btn_quit.IsIn(event.MouseMoveEvent.x, event.MouseMoveEvent.x){
                btn_quit.RenderImg(window,"button_on.png");
            } else {
                btn_quit.RenderImg(window,"button.png");
            }
        }
    }

    // Clear screen
    window.clear();

    // Draw the sprite
    window.draw(sprite);
    window.draw(lsprite);

答案 1 :(得分:1)

您目前正在做的事情在某些方面是不正确的。首先,你不能像这样访问x和y作为静态数据,它根本就不存在。

接下来,SFML事件本质上是联合,这意味着它们的实际内容将取决于您尝试处理的事件类型。您不能为每个事件获取x和y值,至少不能从事件对象获取。如果您有鼠标事件,您将执行以下操作:

if(event.type == sf::Event::MouseMoved) 
{
    // do something with event.mouseMove.x and event.mouseMove.y
}

或者,如果您想在mouseMoved事件范围之外执行此操作,则可以始终使用Mouse类。这包含getPosition方法,该方法将返回包含xy的二维向量:

sf::Mouse::getPosition(); //Absolute coordinates
sf::Mouse::getPosition(window); //Relative to window