我试图找出如何将精灵移动到目标位置。 (通过左键单击一个精灵,然后再次左键单击以将其移动到被单击的位置)。我的代码出了什么问题?如何实现这样的功能。请提前获取任何帮助。
#include <SFML/Graphics.hpp>
#include <iostream>
#include <vector>
int main()
{
sf::RenderWindow mMainWindow(sf::VideoMode(600,600), "Map", sf::Style::Close);
mMainWindow.setFramerateLimit(60);
mMainWindow.setKeyRepeatEnabled(false);
sf::Image image;
image.create(50, 50, sf::Color::Red);
sf::Texture texture;
texture.loadFromImage(image);
std::vector<sf::Sprite> EnemyVector;
std::vector<sf::Vector2f> EnemyPositions;
std::vector<sf::Vector2f> EnemyVelocities;
sf::Sprite* focus = nullptr;
bool move = false;
while (mMainWindow.isOpen())
{
sf::Event event;
bool creating = false;
bool leftclicked = false;
sf::Vector2i mousePos;
while (mMainWindow.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
mMainWindow.close();
break;
case sf::Event::KeyPressed:
creating = (event.key.code == sf::Keyboard::A);
break;
case sf::Event::MouseButtonPressed:
if (event.mouseButton.button == sf::Mouse::Left)
{
leftclicked = true;
mousePos = sf::Vector2i(event.mouseButton.x, event.mouseButton.y);
break;
}
}
}
if (creating)
{
sf::Sprite sprite;
mousePos = (mousePos == sf::Vector2i(0, 0) ? sf::Mouse::getPosition(mMainWindow) : mousePos);
sprite.setTexture(texture);
sprite.setColor(sf::Color::Red);
sprite.setOrigin(static_cast<float>(sprite.getTextureRect().width) / 2, static_cast<float>(sprite.getTextureRect().height) / 2);
sprite.setPosition(static_cast<float>(mousePos.x), static_cast<float>(mousePos.y));
focus=nullptr;
EnemyVector.push_back(sprite);
EnemyPositions.push_back(sf::Vector2f(static_cast<float>(mousePos.x), static_cast<float>(mousePos.y)));
EnemyVelocities.push_back(sf::Vector2f(0,0));
}
if (leftclicked)
{
for (auto& enemy = EnemyVector.rbegin(); enemy != EnemyVector.rend(); ++enemy)
{
if (enemy->getGlobalBounds().contains(static_cast<float>(mousePos.x), static_cast<float>(mousePos.y)))
{
focus = &(*enemy);
move = !move;
break;
}
}
}
if(move)
{
if(focus!=nullptr)
{
focus->move((sf::Mouse::getPosition(mMainWindow).x*0.1 - focus->getPosition().x*0.1),(sf::Mouse::getPosition(mMainWindow).y*0.1 - focus->getPosition().y*0.1)) ;
}
}
mMainWindow.clear();
for (auto& enemy = EnemyVector.rbegin(); enemy != EnemyVector.rend(); ++enemy)
{
mMainWindow.draw(*enemy);
}
mMainWindow.display();
}
return 0;
}
答案 0 :(得分:0)
基本上有两种方式:
两者都需要保留精灵的目标坐标。
使用事件循环方法,您必须修改事件循环以不阻止等待事件,然后在需要时更新精灵坐标并重绘。
如果你使用线程,一个线程可以更新应该移动的所有sprite的坐标,并要求主渲染线程重绘。
应该注意的是,两种方法基本相同,区别仅在于更新精灵的当前位置。