When the view's center is set to the players position each frame, the player movement is fine but when the view is not centered to the players position, the rectangle jitters back and forth when receiving input commands.
Here's my code
#include<SFML/Graphics.hpp>
#include<string>
#include<iostream>
int main()
{
sf::Vector2i screenDimensions(800, 600);
sf::RenderWindow Window;
Window.create(sf::VideoMode(screenDimensions.x, screenDimensions.y), "My First Sfml Game");
//Window.setKeyRepeatEnabled(false);
Window.setVerticalSyncEnabled(true);
sf::Texture bTexture;
sf::Sprite bImage;
if(!bTexture.loadFromFile("Background.png"))
std::cout << "Could not load backgorund image" << std::endl;
bImage.setTexture(bTexture);
sf::RectangleShape rect(sf::Vector2f(20, 20));
rect.setFillColor(sf::Color::Red);
sf::Clock clock;
float moveSpeed = 2000.0f;
sf::View view;
view.reset(sf::FloatRect(0, 0, screenDimensions.x, screenDimensions.y));
view.setViewport(sf::FloatRect(0, 0, 1.0, 1.0));
sf::Vector2f position(screenDimensions.x / 2, screenDimensions.y / 2);
view.setCenter(position);
while(Window.isOpen())
{
clock.restart();
sf::Event Event;
while(Window.pollEvent(Event))
{
switch(Event.type)
{
case sf::Event::Closed:
Window.close();
break;
case sf::Event::KeyPressed:
if(Event.key.code == sf::Keyboard::Escape)
Window.close();
break;
}
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
rect.move(moveSpeed * clock.getElapsedTime().asSeconds(), 0);
else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
rect.move(-moveSpeed * clock.getElapsedTime().asSeconds(), 0);
if(rect.getPosition().x + 10 > screenDimensions.x / 2)
position.x = rect.getPosition().x + 10;
if(rect.getPosition().y + 10 > screenDimensions.y / 2)
position.y = rect.getPosition().y + 10;
view.setCenter(position);
Window.setView(view);
Window.draw(bImage);
Window.draw(rect);
Window.display();
Window.clear();
}
}