Advertisement
TermSpar

Player Class

Jun 30th, 2016
1,814
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.93 KB | None | 0 0
  1. //PLAYER CLASS:
  2. #pragma once
  3.  
  4. #include <iostream>
  5. #include <SFML\Graphics.hpp>
  6.  
  7. class Player{
  8. public:
  9.     Player(){
  10.         //Default
  11.     }
  12.  
  13.     Player(std::string imgDirectory){
  14.         if(!pTexture.loadFromFile(imgDirectory)){
  15.             std::cerr << "Error\n";
  16.         }
  17.         pSprite.setTexture(pTexture);
  18.     }
  19.  
  20.     void drawPlayer(sf::RenderWindow &window){
  21.         window.draw(pSprite);
  22.     }
  23.  
  24.     void movePlayer(char direction, float moveSpeed){
  25.         if(direction == 'u'){
  26.             pSprite.move(0, -moveSpeed);
  27.         }else if(direction == 'd'){
  28.             pSprite.move(0, moveSpeed);
  29.         }else if(direction == 'l'){
  30.             pSprite.move(-moveSpeed, 0);
  31.         }else if(direction == 'r'){
  32.             pSprite.move(moveSpeed, 0);
  33.         }
  34.     }
  35. private:
  36.     sf::Texture pTexture;
  37.     sf::Sprite pSprite;
  38. };
  39.  
  40.  
  41. //MAIN.CPP:
  42. #include <iostream>
  43. #include <SFML/Graphics.hpp>
  44. #include "Player.h"
  45.  
  46. int main(){
  47.     sf::RenderWindow window;
  48.    
  49.     sf::Vector2i centerWindow((sf::VideoMode::getDesktopMode().width/2)-755, (sf::VideoMode::getDesktopMode().height/2)-390);
  50.  
  51.     window.create(sf::VideoMode(1500, 700), "SFML Tutorial", sf::Style::Titlebar | sf::Style::Close);
  52.     window.setPosition(centerWindow);
  53.  
  54.     window.setKeyRepeatEnabled(true);
  55.  
  56.     Player myPlayer("player.png");
  57.  
  58.     //Main Loop:
  59.     while(window.isOpen()){
  60.        
  61.         sf::Event Event;
  62.  
  63.         //Event Loop:
  64.         while(window.pollEvent(Event)){
  65.             switch(Event.type){
  66.  
  67.             case sf::Event::Closed:
  68.                 window.close();
  69.             }
  70.  
  71.             if(sf::Keyboard::isKeyPressed(sf::Keyboard::W)){
  72.                 myPlayer.movePlayer('u', 6.0);
  73.             }else if(sf::Keyboard::isKeyPressed(sf::Keyboard::S)){
  74.                 myPlayer.movePlayer('d', 6.0);
  75.             }else if(sf::Keyboard::isKeyPressed(sf::Keyboard::A)){
  76.                 myPlayer.movePlayer('l', 6.0);
  77.             }else if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)){
  78.                 myPlayer.movePlayer('r', 6.0);
  79.             }
  80.         }
  81.         window.clear();
  82.         myPlayer.drawPlayer(window);
  83.         window.display();
  84.     }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement