I am brand new to SFML and no idea how to use anything. I am a noob to C++ too. However, I want to make a sprite that I have stay within the boundaries of the window, as currently he is not stopping on the screen if I direct him too(naughty sprite!)
Thank you
At the minute I have it so he stays on screen but it's not as fluid at the ones with left and top. My current implementation leads to him "jumping" back and forth when he goes to the right and left.
Here is my code
#include <SFML\Graphics.hpp>
#include <iostream>
#include <string>
int main()
{
enum Direction{ Down , Left, Right, Up};
sf::RenderWindow window(sf::VideoMode(800, 600), "My Game");
sf::Texture playerTexture;
sf::Sprite gameCharacter;
sf::Vector2i source(1, 32);
if (!playerTexture.loadFromFile("Player.png"))
window.setTitle("My Window");
gameCharacter.setTexture(playerTexture);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
window.close();
case sf::Event::KeyPressed:
if (event.key.code == sf::Keyboard::Escape)
window.close();
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
gameCharacter.move(0, -1);
if (gameCharacter.getPosition().y < 0)
gameCharacter.setPosition(sf::Vector2f(gameCharacter.getPosition().x, 0));
source.y = Up;
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
gameCharacter.move(0, 1);
if (gameCharacter.getPosition().y > window.getSize().y)
gameCharacter.setPosition(sf::Vector2f(gameCharacter.getPosition().x ,window.getSize().y - gameCharacter.getGlobalBounds().height));
source.y = Down;
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
gameCharacter.move(1, 0);
if (gameCharacter.getPosition().x > window.getSize().x)
gameCharacter.setPosition(sf::Vector2f(window.getSize().x-gameCharacter.getGlobalBounds().width, gameCharacter.getPosition().y));
source.y = Right;
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
gameCharacter.move(-1,0);
if (gameCharacter.getPosition().x < 0)
gameCharacter.setPosition(sf::Vector2f(0, gameCharacter.getPosition().y));
source.y = Left;
}
source.x++;
if (source.x * 32 >= playerTexture.getSize().x)
source.x = 0;
gameCharacter.setTextureRect(sf::IntRect(source.x * 32, source.y * 32, 32, 32));
window.draw(gameCharacter);
window.display();
window.clear();
}
}