通过按住鼠标按钮移动存储在编队向量中的精灵。问题是:每当我将精灵移动到另一个精灵上时,我会同时移动两个精灵。
我想要的:将sprite1移动到其他spritees2而不改变精灵2的位置或用其他词语:
- 如果点击了矢量的精灵,则在循环中进行测试
- 如果点击了精灵:
按下按钮时移动此精灵,但在此移动时以某种方式停止此移动,以避免移动超过这一个精灵。
到目前为止,这是我的尝试:
while (App.pollEvent(Event))
{
// Window closed
if (Event.type == sf::Event::Closed)
{
return (-1);
}
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
for (size_t k = 0; k < formation.size(); k++)
{
if (isMouseOver(formation[k], App) == true)
{
Mouseposition = sf::Vector2f(sf::Mouse::getPosition(App));
Mouseposition.x = Mouseposition.x - formation[k].getLocalBounds().width / 2;
Mouseposition.y = Mouseposition.y - formation[k].getLocalBounds().height / 2;
formation[k].setPosition(sf::Vector2f(Mouseposition));
Formation_playernames.clear();
Formation_playerinformation.clear();
Formation_Playernames(Font, Formation_playernames, formation, playerlist);
Formation_Playerinformation(Font, Formation_playerinformation, formation, playerlist);
}
}
}
}
形成函数根据形成向量中的位置存储精灵的正确新位置及其颜色 问题是for循环,我可以不用,但这将导致更长的代码。我怎么能这样做?
答案 0 :(得分:3)
您应该构建代码,而不是简单地检查是否按下了鼠标按钮,这样您就可以确切地检查按钮被按下的时间以及何时释放按钮。然后,您可以构建代码,以便按钮的不同按压彼此区分。半伪代码如下
bool button_is_pressed = false;
Sprite* currently_selected_sprite = nullptr;
// main application loop
while (...)
{
...
// other application logic
...
if (!button_is_pressed)
{
if (CheckIfButtonIsPressed())
{
button_is_pressed = true;
// Button was just pressed.
// Select the appropriate sprite by checking
// the mouse coordinates against the positions
// of the sprites.
}
else
{
// Button not being pressed.
// Likely no logic needed here.
}
}
else // button_is_pressed == true
{
if (CheckIfButtonIsPressed())
{
// Button is being held down.
// Implement dragging logic using the
// pointer to the selected sprite.
}
else
{
button_is_pressed = false;
// Button was just released.
// Deselect the sprite.
currently_selected_sprite = nullptr;
}
}
}
或者,您可以处理鼠标事件,这将为您处理大部分逻辑。 http://sfml-dev.org/documentation/2.0/classsf_1_1Event.php
在更像英语的伪代码中,这就是你的功能所在:
if the mouse button is currently pressed
move all the sprites which are under the mouse to be centered on the mouse cursor
else
do nothing
这就是我所建议的
at the moment the mouse button is pressed down
select the sprite which is under the mouse cursor
at the moment the mouse button is released
deselect the selected sprite
if the mouse button is currently pressed, and a sprite is selected
move the selected sprite to the position of the mouse cursor