2017-05-04 71 views
1

SFML不會將子畫面移動超過1個像素(即使持有)。它還會在釋放正在按住的箭頭鍵時將精靈移回到其設定位置。SFML不能正確移動子畫面

void Engine::mainLoop() { 
    //Loop until window is closed 
    while (window->isOpen()) { 
      processInput(); 
      update(); 
      sf::Sprite test; 
      sf::Texture texTest; 
      texTest.loadFromFile("img.png"); 
      test.setTexture(texTest); 
      test.setPosition(50, 50); 
      if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Up)) 
       test.move(0, -1); 
      if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Down)) 
       test.move(0, 1); 
      if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Left)) 
       test.move(-1, 0); 
      if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Right)) 
       test.move(1, 0); 
      window->clear(sf::Color::Black); 
      window->draw(test); 
      renderFrame(); 
      window->display(); 
    } 
} 

+1

你總是調用'setPosition'所以它會在你身邊50,50 + -1 – vu1p3n0x

+0

我覺得很愚蠢 –

回答

1

在評論提的是,你總是設定的位置之上,你也重現精靈每一幀,所以它的位置將永遠沒有你甚至不重置調用

作爲一個方面說明,你也加載每幀的紋理,這是非常低效!

這應該是你追求的:

void Engine::mainLoop() { 
    sf::Sprite test; 
    sf::Texture texTest; 
    texTest.loadFromFile("img.png"); 
    test.setTexture(texTest); 
    test.setPosition(50, 50); 

//Loop until window is closed 
while (window->isOpen()) { 
     processInput(); 
     update(); 
     if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Up)) 
      test.move(0, -1); 
     if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Down)) 
      test.move(0, 1); 
     if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Left)) 
      test.move(-1, 0); 
     if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Right)) 
      test.move(1, 0); 
     window->clear(sf::Color::Black); 
     window->draw(test); 
     renderFrame(); 
     window->display(); 
} 
}