2017-05-04 77 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(); 
} 
}