i am new to SFML and was wandering why my player will only move at a certain distance witch is a very small distance.
Here is my code: game.cpp:
#include <SFML/Graphics.hpp>
int main() {
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML Game!");
while(window.isOpen()) {
sf::Event event;
while(window.pollEvent(event)) {
if(event.type == sf::Event::Closed)
window.close();
}
sf::Font font;
if(!font.loadFromFile("../resources/Lets Coffee.ttf"))
return EXIT_FAILURE;
sf::Text text("Use the WASD keys to move the player around", font, 20);
text.setPosition(5, 5);
// make a player sprite
sf::Texture *playerTexture;
playerTexture = new sf::Texture();
if(!playerTexture->loadFromFile("../resources/Bluey.png"))
return EXIT_FAILURE;
sf::RectangleShape player(sf::Vector2f(128, 128));
player.setPosition(400, 300);
player.setTexture(playerTexture);
player.setOutlineColor(sf::Color::Black);
player.setOutlineThickness(10);
// Here is my distance problem:
if(sf::Keyboard::isKeyPressed(sf::Keyboard::W)) {
player.move(0, -5);
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {
player.move(0, 5);
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {
player.move(-5, 0);
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {
player.move(5, 0);
}
window.clear();
window.draw(text);
window.draw(player);
window.display();
}
return 0;
}
Could any of you help?, and am i doing something wrong?, if i am the please tell me!
Credit : Gerard0097
The issue is that your are creating the player object within your main loop, so each cycle you create a new object and that's why is seems like it's moving a short distance but it's just different objects moving once and then being destroyed
Credit : Me
Just create player and texture before main loop (game loop) :
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML Game!");
sf::Font font;
if(!font.loadFromFile("../resources/Lets Coffee.ttf"))
return EXIT_FAILURE;
sf::Text text("Use the WASD keys to move the player around", font, 20);
text.setPosition(5, 5);
sf::Texture *playerTexture;
playerTexture = new sf::Texture();
if(!playerTexture->loadFromFile("../resources/Bluey.png"))
return EXIT_FAILURE;
sf::RectangleShape player(sf::Vector2f(128, 128));
player.setPosition(400, 300);
player.setTexture(playerTexture);
player.setOutlineColor(sf::Color::Black);
player.setOutlineThickness(10);
and then your game loop :
while (game.isOpen) {
// Your Game Logic, Event Handling and drawings
}