使用 SFML 获取点击位置 [英] Getting clicked position using SFML

查看:62
本文介绍了使用 SFML 获取点击位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在自己​​学习SFML,并试图弄清楚如何在bposXbposY处打印出点击区域的位置> pollevent 部分.这是我的代码:

I'm currently learning SFML on my own, and trying to figure out how to print out the position of the clicked area at bposX and bposY in the pollevent section. Thi s is my codes:

sf::RectangleShape smallRectangle (float width = 1.0f, float height = 1.0f, 
                                sf::Vector2f position = sf::Vector2f(1.0f,1.0f),
                                const sf::Color& myFillColor = sf::Color(0,51, 51)
                                )
{
  sf::RectangleShape sboard;
  sf::Vector2f myRectangleSize(width, height);
  sboard.setSize(myRectangleSize);
  sboard.setPosition(position);
  sboard.setFillColor(myFillColor);
  return sboard;
}

<小时>

case sf::Event::MouseButtonPressed:
                switch(event.mouseButton.button)
                    case sf::Mouse::Left:
                    {
                        float bposX = sboard.getPosition().x;
                        float bposY = sboard.getPosition().y;
                        cout << "Current Position : ";
                        cout << bposX << " " << bposY << endl;
                    break;
                    }   

<小时>

for(int i=0; i < sgridSize; i++)
{
    for (int j = 0; j < sgridSize; j++)
    {
        window.draw(sgrid[i][j]);
        sf::FloatRect sgridBounds = sgrid[i][j].getGlobalBounds();
        if(sgridBounds.contains((sf::Vector2f)pointerPos))
        {
            shighlightCell.setPosition(sgrid[i][j].getPosition());
            window.draw(shighlightCell);
            if(sf::Mouse::isButtonPressed(sf::Mouse::Left))
            {
                sgrid[i][j].setFillColor(sf::Color::Green);
            }
        }
    }
}

当我点击矩形时,它只显示 1 1,基于我的 Vector2f 位置.

When I click in rectangle it only displays 1 1, based on my Vector2f position.

推荐答案

假设我正确阅读了你的代码,sboard 是一个 sf::RectangleShape.很有可能你真的想要鼠标的位置,而不是这个矩形.鼠标位置通过静态函数 sf::Mouse::getPosition() 给出,它给出相对于桌面的坐标或 sf::Mouse::getPosition(window)为您提供鼠标相对于 sf::Windowsf::RenderWindow 实例的位置.

Assuming I'm reading your code properly, sboard is a sf::RectangleShape. Chances are you actually want the position of the mouse, not this rectangle. Mouse position is given through the static function sf::Mouse::getPosition() which gives coordinates relative to desktop or sf::Mouse::getPosition(window) which will give you the position of the mouse relative to a sf::Window or sf::RenderWindow instance.

我建议您在学习基础知识的同时通读 SFML 网站上的教程.这个立即有用.

I suggest reading through the tutorials on the SFML website while you're learning the basics. This one is immediately useful.

这篇关于使用 SFML 获取点击位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆