C++/SFML 2.1 Player Movement


SUBMITTED BY: PlumpDolphin

DATE: July 15, 2016, 12:59 a.m.

FORMAT: C++

SIZE: 2.5 kB

HITS: 256

  1. //This is a comment
  2. ///This is a comment too
  3. /*This is also a comment*/
  4. /*
  5. Hey, this is a basic player movement program written in C++
  6. with SFML 2.1... The comments written are to help you understand
  7. what is going on at each specific line. Of course, I don't have
  8. enough time to comment them all, so I simply commented the more
  9. important ones. If you have any further questions, please feel
  10. free to ask in the comments section below. Enjoy!
  11. */
  12. #include <iostream>
  13. #include <SFML/Graphics.hpp>
  14. using namespace std;
  15. int main()
  16. {
  17. //Intitiating the Window
  18. sf::RenderWindow game(sf::VideoMode(640, 480), "Player Movement");
  19. game.setFramerateLimit(60); //Limiting the framerate for constant speed on all CPUs
  20. sf::Event gameEvent;
  21. //Initiating the Player Object
  22. sf::RectangleShape player(sf::Vector2f(64, 64));
  23. player.setFillColor(sf::Color::Blue); // Specifies the rectangle's color
  24. float playerSpeed = 2; /*Specifies the player's movement speed
  25. (Which is used later in the Keyboard Input section)*/
  26. while(game.isOpen())
  27. {
  28. //Handling Window Events
  29. while(game.pollEvent(gameEvent))
  30. {
  31. switch(gameEvent.type)
  32. {
  33. case sf::Event::Closed:
  34. game.close();
  35. break;
  36. default:
  37. break;
  38. }
  39. }
  40. //Keyboard Input
  41. if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) //When the Up Arrow is pressed...
  42. {
  43. player.move(0, -playerSpeed); //Move 0 pixels horizontally and 1 up vertically
  44. }
  45. if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) //When the Down Arrow is pressed...
  46. {
  47. player.move(0, playerSpeed); //Move 0 pixels horizontally and 1 down vertically
  48. }
  49. if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) //When the Left Arrow is pressed...
  50. {
  51. player.move(-playerSpeed, 0); //Move 1 pixels to the left horizontally and 0 vertically
  52. }
  53. if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) //When the Right Arrow is pressed...
  54. {
  55. player.move(playerSpeed, 0); //Move 1 pixels to the right horizontally and 0 vertically
  56. }
  57. //Rendering
  58. game.clear();
  59. game.draw(player);
  60. game.display();
  61. }
  62. return (0);
  63. }

comments powered by Disqus