SpriteComponent.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // ----------------------------------------------------------------
  2. // From Game Programming in C++ by Sanjay Madhav
  3. // Copyright (C) 2017 Sanjay Madhav. All rights reserved.
  4. //
  5. // Released under the BSD License
  6. // See LICENSE in root directory for full details.
  7. // ----------------------------------------------------------------
  8. #include "SpriteComponent.h"
  9. #include "Texture.h"
  10. #include "Shader.h"
  11. #include "Actor.h"
  12. #include "Game.h"
  13. SpriteComponent::SpriteComponent(Actor* owner, int drawOrder)
  14. :Component(owner)
  15. ,mTexture(nullptr)
  16. ,mDrawOrder(drawOrder)
  17. ,mTexWidth(0)
  18. ,mTexHeight(0)
  19. {
  20. mOwner->GetGame()->AddSprite(this);
  21. }
  22. SpriteComponent::~SpriteComponent()
  23. {
  24. mOwner->GetGame()->RemoveSprite(this);
  25. }
  26. void SpriteComponent::Draw(Shader* shader)
  27. {
  28. if (mTexture)
  29. {
  30. // Scale the quad by the width/height of texture
  31. Matrix4 scaleMat = Matrix4::CreateScale(
  32. static_cast<float>(mTexWidth),
  33. static_cast<float>(mTexHeight),
  34. 1.0f);
  35. Matrix4 world = scaleMat * mOwner->GetWorldTransform();
  36. // Since all sprites use the same shader/vertices,
  37. // the game first sets them active before any sprite draws
  38. // Set world transform
  39. shader->SetMatrixUniform("uWorldTransform", world);
  40. // Set current texture
  41. mTexture->SetActive();
  42. // Draw quad
  43. glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);
  44. }
  45. }
  46. void SpriteComponent::SetTexture(Texture* texture)
  47. {
  48. mTexture = texture;
  49. // Set width/height
  50. mTexWidth = texture->GetWidth();
  51. mTexHeight = texture->GetHeight();
  52. }