A 2D tile-based sandbox game.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ItemStackEntity.cc 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include "ItemStackEntity.h"
  2. #include <random>
  3. ItemStackEntity::ItemStackEntity(
  4. const Swan::Context &ctx, Swan::Vec2 pos, const std::string &item):
  5. ItemStackEntity() {
  6. static std::uniform_real_distribution vx(-2.3f, 2.3f);
  7. static std::uniform_real_distribution vy(-2.3f, -1.2f);
  8. body_.pos = pos;
  9. item_ = &ctx.world.getItem(item);
  10. physics_.vel += Swan::Vec2{ vx(ctx.world.random_), vy(ctx.world.random_) };
  11. }
  12. ItemStackEntity::ItemStackEntity(const Swan::Context &ctx, const PackObject &obj):
  13. ItemStackEntity() {
  14. deserialize(ctx, obj);
  15. }
  16. void ItemStackEntity::draw(const Swan::Context &ctx, Swan::Win &win) {
  17. SDL_Rect rect = item_->image_.frameRect();
  18. SDL_Texture *tex = item_->image_.texture_.get();
  19. Swan::TexColorMod darken(tex, 220, 220, 220);
  20. win.showTexture(body_.pos, tex, &rect,
  21. { .hscale = 0.5, .vscale = 0.5 });
  22. }
  23. void ItemStackEntity::update(const Swan::Context &ctx, float dt) {
  24. physics(ctx, dt, { .mass = MASS, .bounciness = 0.6 });
  25. }
  26. void ItemStackEntity::tick(const Swan::Context &ctx, float dt) {
  27. despawnTimer_ -= dt;
  28. if (despawnTimer_ <= 0)
  29. despawn(ctx);
  30. }
  31. void ItemStackEntity::deserialize(const Swan::Context &ctx, const PackObject &obj) {
  32. body_.pos = obj.at("pos").as<Swan::Vec2>();
  33. item_ = &ctx.world.getItem(obj.at("item").as<std::string>());
  34. }
  35. Swan::Entity::PackObject ItemStackEntity::serialize(const Swan::Context &ctx, msgpack::zone &zone) {
  36. return {
  37. { "pos", msgpack::object(body_.pos, zone) },
  38. { "tile", msgpack::object(item_->name_, zone) },
  39. };
  40. }