【发布时间】:2014-07-16 03:51:16
【问题描述】:
我已经在网上彻底搜索了几天,但无法为以下问题找到任何解决方案:它是关于 C++ 和 SFML 2.1。我希望能够通过中间(按钮)单击它们(然后对它们做一些事情)来选择“游戏内”生成的单个精灵。如果在任何给定位置(重叠)有多个精灵,那么我想选择最上面的一个。我正在使用一个列表,每当我尝试选择任何 Sprite 时,只有最后创建的那个“反应”正确(即打印控制台文本)。非常感谢您的帮助。
完整代码:
#include <SFML/Graphics.hpp>
#include <iostream>
#include <list>
int main()
{
sf::RectangleShape rectangle;
rectangle.setSize(sf::Vector2f(1000, 600));
rectangle.setFillColor(sf::Color(100,80,100,100));
rectangle.setPosition(0, 0);
sf::Sprite newSprite;
sf::FloatRect rightBound = rectangle.getGlobalBounds();
sf::FloatRect unitrect = newSprite.getGlobalBounds();
sf::RenderWindow mMainWindow(sf::VideoMode(1000, 600), "Map");
mMainWindow.setFramerateLimit(60);
sf::Texture unittexture;
unittexture.loadFromFile("warrior.png");
std::list<sf::Sprite> EnemyList;
std::list<sf::Sprite>::iterator EnemyIt;
while (mMainWindow.isOpen())
{
sf::Event event;
while (mMainWindow.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
mMainWindow.close();
}
if (event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Middle)
if(newSprite.getGlobalBounds().contains(mMainWindow.mapPixelToCoords(sf::Mouse::getPosition(mMainWindow))))
std::cout << "Unit selected" << std::endl;
if(event.type == sf::Event::MouseButtonPressed)
if(event.mouseButton.button == sf::Mouse::Right)
{
sf::Vector2f mousecoords(mMainWindow.mapPixelToCoords(sf::Vector2i(event.mouseButton.x, event.mouseButton.y)));
EnemyList.remove_if([=](sf::Sprite unitsprite){return unitsprite.getGlobalBounds().contains(mousecoords); });
}
if(event.type == sf::Event::MouseButtonPressed)
if(event.mouseButton.button == sf::Mouse::Left)
if (rectangle.getGlobalBounds().contains(mMainWindow.mapPixelToCoords(sf::Mouse::getPosition(mMainWindow))))
{
newSprite.setTexture(unittexture);
newSprite.setPosition(sf::Mouse::getPosition(mMainWindow).x,sf::Mouse::getPosition(mMainWindow).y);
EnemyList.push_back(newSprite);
}
}
for(EnemyIt = EnemyList.begin();EnemyIt != EnemyList.end();EnemyIt++)
{
mMainWindow.draw(*EnemyIt);
}
mMainWindow.display();
mMainWindow.clear(sf::Color(0, 200, 0, 255));
}
return 0;
}
【问题讨论】:
-
检查鼠标中键事件时,您似乎只检查点击是否在最新创建的精灵的范围内。这是故意的吗?
-
暂时是故意的,因为我不知道。但我希望它检查是否在“最顶层”精灵的范围内。
-
等等,有什么问题? “我正在使用一个列表,每当我尝试选择任何 Sprite 时,只有最后创建的那个,“反应”正确......”似乎只检查最新的 sprite 会导致这种情况,但它是故意的?
-
好吧,不,这不是故意的 :-) 这只是为了表明我走了多远。 (不是很远:-))