2
« on: October 30, 2017, 08:49:01 pm »
Hi everyone.
I'm trying to use viewports as moveable objects to implement cameras which can be placed on the game scene and used as regular objects.
From what I've tried already the basic movement works fairly well, but I've found an unpleasant behaviour, which I can't fix - when the camera (viewport) reaches the screen border the objects inside it shift on 1-2 pixels in the opposite to the movement direction.
I've tried to apply various offsets in the sf::View:setCenter() manually to counter this effect, but it didn't do the trick.
Here's the minimal code example which reproduces the problem:
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
int main()
{
const sf::Vector2f windowSize(1280,720);
sf::RenderWindow window(sf::VideoMode(static_cast<unsigned int>(windowSize.x),
static_cast<unsigned int>(windowSize.y)), "SFML");
sf::RectangleShape quad;
quad.setFillColor(sf::Color::White);
quad.setSize(sf::Vector2f(100,100));
quad.setPosition(100,100);
const sf::Vector2f cameraSize(640,480);
sf::View camera;
camera.setSize(cameraSize);
sf::RectangleShape cameraBackground;
cameraBackground.setFillColor(sf::Color(50,50,50,255));
cameraBackground.setSize(cameraSize);
sf::Clock clock;
sf::Vector2f coord;
const int speed = 100;
while (window.isOpen()){
sf::Event event;
while (window.pollEvent(event)){
if (event.type == sf::Event::Closed)
window.close();
}
sf::Time elapsed = clock.restart();
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
coord.y -= speed * elapsed.asSeconds();
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
coord.y += speed * elapsed.asSeconds();
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
coord.x -= speed * elapsed.asSeconds();
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
coord.x += speed * elapsed.asSeconds();
camera.setCenter(coord + sf::Vector2f(cameraSize.x / 2, cameraSize.y / 2));
camera.setViewport(sf::FloatRect(coord.x / windowSize.x,
coord.y / windowSize.y,
cameraSize.x / windowSize.x,
cameraSize.y / windowSize.y));
cameraBackground.setPosition(coord);
window.clear();
window.setView(camera);
window.draw(cameraBackground);
window.draw(quad);
window.display();
}
return 0;
}
(Use direction arrows to move camera(grey square), when it crosses the screen's border, the object on camera (white square) will jitter slightly)
Any help would be appreciated.