Hello to everyone! I'm learning sfml and I'm trying to move a rectangleShape based on input. The problem is that when i press a key for change direction, it starts moving from top, and not from last reached position. It has to be a grid-like movement. Can someone help me with this? How should I change the logic to achive that?
#include <iostream>
#include <cstdlib>
#include "game.h"
using namespace std;
int main()
{
sf::RenderWindow window(sf::VideoMode(600, 600), "Move shape");
sf::RectangleShape shape(sf::Vector2f(20, 20));
shape.setFillColor(sf::Color::Red);
shape.setPosition(sf::Vector2f(20, 20));
int speed = 15;
Clock clock;
float felapsed = 0;
sf::Vector2f dir(1, 0);
int x = 9;
int y = 0;
while (window.isOpen())
{
sf::Event e;
while (window.pollEvent(e))
{
if (e.type == sf::Event::Closed)
window.close();
}
if (sf::Keyboard::isKeyPressed(Keyboard::Up)) dir = sf::Vector2f(0, -1);
else if (sf::Keyboard::isKeyPressed(Keyboard::Down)) dir = sf::Vector2f(0, 1);
else if (sf::Keyboard::isKeyPressed(Keyboard::Right)) dir = sf::Vector2f(1, 0);
else if (sf::Keyboard::isKeyPressed(Keyboard::Left)) dir = sf::Vector2f(-1, 0);
float frameTime = 1.0f / speed;
window.clear();
if (felapsed >= frameTime)
{
if (dir == sf::Vector2f(1, 0))
x++;
else if (dir == sf::Vector2f(-1, 0))
x--;
else if (dir == sf::Vector2f(0, 1))
y++;
else if (dir == sf::Vector2f(0, -1))
y--;
shape.setPosition(dir.x*x*16, dir.y * y * 16);
window.draw(shape);
window.display();
felapsed -= frameTime;
}
felapsed += clock.restart().asSeconds();
}
return 0;
}