2017-08-12 144 views
1

我在做一個簡單的蛇遊戲,但是當我嘗試移動我的蛇的一部分時 它到了0,0。 我把蛇的所有部分都放在一個向量中。 但是當我做類似sfml - vector [0] .getPosition()返回0

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

我認爲這是與指針有關? 但我不知道如何修復...

回答

1

轉儲那些全球snakeN變量!如果您想擁有100個單元格,您是否要將所有內容都聲明爲snake100?你的向量正在存儲副本(那些在(0,0)上保持不變),你應該在其上執行所有的邏輯。


使所有其他全局變量局部爲函數或類的成員,並在需要時使用函數參數。

movingDirection應該是enum

updatePos其目前的簽名應該是return的東西。

+1

感謝它的作品也感謝您的額外建議! –