gpt4 book ai didi

c++ - 在 vector 中移动 Sprite

转载 作者:行者123 更新时间:2023-11-30 02:47:28 25 4
gpt4 key购买 nike

我通过按住鼠标按钮移动存储在 formationvector 中的 Sprite 。问题是:每当我将 Sprite 移到另一个 Sprite 上时,我都会同时移动两个 Sprite 。

我想要的是:将 sprite1 移动到其他 sprites2 上而不改变 sprite 2 的位置或换句话说:

-如果点击 vector 的 Sprite ,则循环测试

-如果 Sprite 被点击:

按下按钮时移动这个 Sprite ,但在移动时以某种方式停止移动以避免移动不止一个 Sprite 。

到目前为止,这是我的尝试:

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);
}
}
}
}

编队函数将 Sprite 的正确新位置及其基于位置的颜色存储到编队 vector 中问题是 for 循环,我可以不用它,但这会导致代码更长。我该怎么做?

最佳答案

不是简单地检查鼠标按钮是否被按下,您应该构建您的代码,以便您可以准确地检查按钮何时被按下以及何时被释放。然后,您可以构建代码,以便区分不同的按钮按下操作。半伪代码如下

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

关于c++ - 在 vector 中移动 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22737644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com