Collidable.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /**
  2. * Triangles
  3. * Copyright (C) 2016 POSITIVE MENTAL ATTITUDE
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, version 3 of the License.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #include "Collidable.hpp"
  18. Collidable::~Collidable()
  19. {
  20. _cmap.clear();
  21. _cbanned.clear();
  22. }
  23. void Collidable::genCollisionBox(std::string file, sf::Vector2f size)
  24. {
  25. sf::Image img;
  26. img.loadFromFile(file);
  27. _cmap.reserve((img.getSize().x * img.getSize().y) / 10);
  28. _cbanned.reserve((img.getSize().x * img.getSize().y) / 2);
  29. for(unsigned int i = 0; i < img.getSize().x; ++i)
  30. for(unsigned int j = 0; j < img.getSize().y; ++j)
  31. if(img.getPixel(i, j).r == 255)
  32. _cmap.push_back(sf::Vector2f(int(i - size.x), int(j - size.y)));
  33. }
  34. void Collidable::setPointCount(unsigned pointCount)
  35. {
  36. _pointCount = pointCount;
  37. }
  38. void Collidable::updateTransform(sf::Transform transform)
  39. {
  40. _transform = transform;
  41. }
  42. int Collidable::pixelPerfect(Foreground& foreground)
  43. {
  44. unsigned tileSize = foreground.getTileSize();
  45. for(unsigned k = 0; k < _cmap.size(); ++k)
  46. {
  47. sf::Vector2i vec = (sf::Vector2i)_transform.transformPoint(_cmap[k]);
  48. if(vec.x < 0) vec.x = 0;
  49. if(vec.y < 0) vec.y = 0;
  50. if(vec.x >= (signed int)foreground.getSize().x) vec.x = foreground.getSize().x - 1;
  51. if(vec.y >= (signed int)foreground.getSize().y) vec.y = foreground.getSize().y - 1;
  52. if(foreground.tileAlpha(vec.x / tileSize, vec.y / tileSize, vec.x % tileSize, vec.y % tileSize) > 0)
  53. return k;
  54. }
  55. return -1;
  56. }