【问题标题】:Mouse position and click detect in sfmlsfml 中的鼠标位置和点击检测
【发布时间】:2012-06-13 07:19:45
【问题描述】:
int Game::MouseOnDot(float x, float y, RenderWindow &renderWindow) {
    Rect<int> Dot;
    Event event;
    Dot.left = x;
    Dot.top = y;
    Dot.width = 20;
    Dot.height = 20;
    while (renderWindow.pollEvent(event)) {
        float Mx = sf::Mouse::getPosition().x;
        float My = sf::Mouse::getPosition().y;
        if (event.type == Event::MouseButtonReleased&&Mx > x && Mx < Dot.height && My > y && My < Dot.width){
                return 1;
        }
            else
                return 0;
    }
}

我不知道为什么如果在点上按下按钮它会返回 1 告诉其他函数关闭窗口,这将不起作用。我在鼠标位置上做错了吗?

while (renderWindow.isOpen()) {
        processEvents(renderWindow);
        float Time = clock.getElapsedTime().asSeconds();
        float TimeDifference = Time - LastUpdateTime;
        if (TimeDifference >= UpdateTime) {
            processEvents(renderWindow);
            y += 3;
            if (y <= 770) {
                if(Game::MouseOnDot(x, y, renderWindow)==1)
                                    renderWindow.close();
                Game::Spawn(renderWindow, Green_Dots, x, y);
                LastUpdateTime = Time;
                return;

当 MouseOnDot 返回 0 或 1 时,我仍然无法工作我在这里粘贴部分。它不会关闭窗口,我不知道为什么??

【问题讨论】:

    标签: c++ sfml


    【解决方案1】:

    使用 sf::Mouse::getPosition().x 返回相对于桌面的位置,如果你想要它相对于你的 renderWindow 你需要做: sf::Mouse::getPosition(renderWindow).x

    那么 Attila 关于鼠标/点的比较是完全正确的 :)

    【讨论】:

      【解决方案2】:

      我认为您的问题是您将位置与 x 坐标和高度进行比较。您需要比较 x 和 x+height(对于 y 坐标/宽度类似)

      试试:

      if (event.type == Event::MouseButtonReleased && 
          Mx > x && Mx < x + Dot.height &&
          My > y && My < y + Dot.width) {
        //...
      }
      

      【讨论】:

      • @Itsmeyxc - 首先,你从哪里来? -- 你确定要进入if (y &lt;= 770) 分支吗?其次,无论 MouseOnDot() 返回 0 还是 1,您都在调用 Game::Spawn(renderWindow,...),无论它在 if 分支之外——我假设 Spawn() 将为您创建一个新窗口
      猜你喜欢
      • 2015-08-03
      • 1970-01-01
      • 2015-04-04
      • 1970-01-01
      • 2018-11-06
      • 2011-11-08
      • 2020-04-18
      • 2014-10-19
      • 2013-11-18
      相关资源
      最近更新 更多