Advertisement
Guest User

SlashC++Programmer

a guest
Jul 7th, 2016
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.07 KB | None | 0 0
  1. #include <SFML/Graphics.hpp>
  2. #include <vector>
  3. #include <iostream>
  4. #include "Bullet.h"
  5. #include "BulletPool.h"
  6. #include "Player.h"
  7.  
  8. int main()
  9. {
  10.     sf::RenderWindow window(sf::VideoMode(640, 480), "Demo");
  11.  
  12.     // flags
  13.     bool isFiring = false;
  14.  
  15.     // Define Objects:
  16.     Player player(sf::Vector2f(50,50));
  17.     BulletPool pool(Bullet(), 10); // create 10 bullets in the pool
  18.     std::vector<Bullet> bullets;
  19.     bullets.reserve(10); // reserve memory
  20.  
  21.     while (window.isOpen())
  22.     {
  23.         sf::Event event;
  24.         while (window.pollEvent(event))
  25.         {
  26.             if (event.type == sf::Event::Closed)
  27.                 window.close();
  28.  
  29.                 if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space)){
  30.                     isFiring = true;
  31.                 }
  32.         }
  33.  
  34.  
  35.          window.clear();
  36.  
  37.          // fire bullet
  38.         if(isFiring == true)
  39.         {
  40.             if(bullets.size() < 10) // make sure the bullets don't go over 10
  41.             {
  42.                 Bullet &newBullet = pool.GetBullet(); // get a bullet from the pool by reference
  43.                 newBullet.SetPos(sf::Vector2f(player.GetX(), player.GetY()));
  44.                 bullets.push_back(newBullet); // add the bullet to the vector
  45.             }
  46.             isFiring = false;
  47.         }
  48.  
  49.         // update bullet
  50.         for( int i = bullets.size()-1; i >= 0; i--)
  51.         {
  52.             bullets[i].Draw(window);
  53.             bullets[i].Fire(3);
  54.  
  55.             // if bullet goes past the screen
  56.             if(bullets[i].GetRight() > 650)
  57.             {
  58.                 bullets.erase(bullets.begin()); // delete element
  59.  
  60.                 Bullet &oldBullet = bullets[i]; // get reference from old bullet
  61.                 pool.ReturnBullet(oldBullet); // pass the old bullet back to the pool by reference
  62.             }
  63.         }
  64.  
  65.         player.Draw(window);
  66.         window.display();
  67.  
  68.         // debugg information making sure it doesn't create a new bullet that is over 10
  69.         std::cout << "bullets in vector: " <<  bullets.size() << '\n';
  70.  
  71.  
  72.     }
  73.  
  74.     return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement