我正在制作一个简单的蛇游戏,但是当我尝试移动蛇的一部分时 它去了0,0。 我将蛇的所有部分都放在一个 vector 中。 但是当我做类似的事情时
vector[0].getPosition()
//(In my code: snakeParts[0].getPosition())
它只返回 0,0。 编译时我也没有收到任何错误。 这是我的代码:
#include <SFML/Graphics.hpp>
#include <iostream>
#include <string>
#include <unistd.h>
#include <vector>
using namespace std;
sf::RenderWindow App(sf::VideoMode(854, 480), "Snake");
sf::RectangleShape snake;
sf::RectangleShape snake2;
vector<sf::RectangleShape> snakeParts;
string movingDirection = "Right";
int updatePos() {
snakeParts[1].setPosition(snakeParts[0].getPosition()); //Where my problem lies
if (movingDirection == "Left") {
snake.move(-32,0);
}
else if (movingDirection == "Right") {
snake.move(32,0);
}
else if (movingDirection == "Up") {
snake.move(0,-32);
}
else if (movingDirection == "Down") {
snake.move(0,32);
}
//for (int i=0; i<snakeParts.size(); i++) {
//int target = snakeParts.size()-i;
}
int main()
{
snake.setSize(sf::Vector2f(32, 32));
snake.setFillColor(sf::Color::Green);
snake2.setSize(sf::Vector2f(32, 32));
snake2.setFillColor(sf::Color::Red);
snakeParts.push_back(snake);
snakeParts.push_back(snake2);
while (App.isOpen())
{
sf::Event event;
while (App.pollEvent(event))
{
if (event.type == sf::Event::Closed)
App.close();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
movingDirection = "Left";
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
movingDirection = "Right";
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
movingDirection = "Down";
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
movingDirection = "Up";
}
}
usleep(100000);
//cout << movingDirection << endl;
updatePos();
App.clear();
App.draw(snake);
App.draw(snake2);
App.display();
}
return 0;
}
我认为这与指针有关? 但我不知道该如何解决...
最佳答案
转储那些全局 snakeN
变量!如果您想拥有 100 个单元格,您是否要声明直到 snake100
的所有内容?您的 vector 正在存储拷贝(那些在 (0, 0) 上保持不变),您应该在其上执行所有逻辑。
将所有其他全局变量设为函数或类成员的局部变量,并在需要时使用函数参数。
movingDirection
应该是一个 enum
。
updatePos
及其当前签名应该返回
一些东西。
关于c++ - sfml - vector[0].getPosition() 返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45651611/