SpriteComponent.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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.txt for full details.
  7. // ----------------------------------------------------------------
  8. #include "SpriteComponent.h"
  9. #include "Actor.h"
  10. #include "Game.h"
  11. SpriteComponent::SpriteComponent(Actor* owner, int drawOrder)
  12. :Component(owner)
  13. ,mTexture(nullptr)
  14. ,mDrawOrder(drawOrder)
  15. ,mTexWidth(0)
  16. ,mTexHeight(0)
  17. {
  18. mOwner->GetGame()->AddSprite(this);
  19. }
  20. SpriteComponent::~SpriteComponent()
  21. {
  22. mOwner->GetGame()->RemoveSprite(this);
  23. }
  24. void SpriteComponent::Draw(SDL_Renderer* renderer)
  25. {
  26. if (mTexture)
  27. {
  28. SDL_Rect r;
  29. // Scale the width/height by owner's scale
  30. r.w = static_cast<int>(mTexWidth * mOwner->GetScale());
  31. r.h = static_cast<int>(mTexHeight * mOwner->GetScale());
  32. // Center the rectangle around the position of the owner
  33. r.x = static_cast<int>(mOwner->GetPosition().x - r.w / 2);
  34. r.y = static_cast<int>(mOwner->GetPosition().y - r.h / 2);
  35. // Draw (have to convert angle from radians to degrees, and clockwise to counter)
  36. SDL_RenderCopyEx(renderer,
  37. mTexture,
  38. nullptr,
  39. &r,
  40. -Math::ToDegrees(mOwner->GetRotation()),
  41. nullptr,
  42. SDL_FLIP_NONE);
  43. }
  44. }
  45. void SpriteComponent::SetTexture(SDL_Texture* texture)
  46. {
  47. mTexture = texture;
  48. // Set width/height
  49. SDL_QueryTexture(texture, nullptr, nullptr, &mTexWidth, &mTexHeight);
  50. }