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

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