Triangle.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 "Triangle.hpp"
  18. #include <iostream>
  19. #include <cmath>
  20. Triangle::Triangle(): _texture(nullptr), _size(100.f)
  21. {
  22. _vertices.setPrimitiveType(sf::Triangles);
  23. _vertices.resize(3);
  24. _vertices[0].color = sf::Color(255, 255, 255, 255);
  25. _vertices[1].color = sf::Color(255, 255, 255, 255);
  26. _vertices[2].color = sf::Color(255, 255, 255, 255);
  27. setPosition(500.f, 300.f);
  28. redraw();
  29. }
  30. float Triangle::getSize()
  31. {
  32. return _size;
  33. }
  34. void Triangle::setSize(float size)
  35. {
  36. _size = size;
  37. redraw();
  38. }
  39. void Triangle::vertexFit()
  40. {
  41. if(_texture == nullptr)
  42. return;
  43. _vertices[0].texCoords = sf::Vector2f(_texture->getSize().x / 2, 0);
  44. _vertices[1].texCoords = sf::Vector2f(_texture->getSize().x, _texture->getSize().y);
  45. _vertices[2].texCoords = sf::Vector2f(0, _texture->getSize().y);
  46. }
  47. void Triangle::setTexture(sf::Texture& texture)
  48. {
  49. _texture = &texture;
  50. vertexFit();
  51. }
  52. void Triangle::setColor(sf::Color color)
  53. {
  54. _vertices[0].color = color;
  55. _vertices[1].color = color;
  56. _vertices[2].color = color;
  57. }
  58. void Triangle::setColor(unsigned r, unsigned g, unsigned b, unsigned a)
  59. {
  60. setColor(sf::Color(r, g, b, a));
  61. }
  62. void Triangle::redraw()
  63. {
  64. double degree = 3.14159265358 / 180.;
  65. _vertices[0].position = sf::Vector2f(0, -_size);
  66. _vertices[1].position = sf::Vector2f(std::sin(135.f * degree) * _size, -std::cos(135.f * degree) * _size);
  67. _vertices[2].position = sf::Vector2f(std::sin(225.f * degree) * _size, -std::cos(225.f * degree) * _size);
  68. }
  69. void Triangle::draw(sf::RenderTarget& target, sf::RenderStates states) const
  70. {
  71. states.transform *= getTransform();
  72. if(_texture != nullptr)
  73. states.texture = (_texture);
  74. target.draw(_vertices, states);
  75. }