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.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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, Cygnet::Renderer &rnd) {
  17. // TODO: decrease brightness?
  18. rnd.drawTile(item_->id, Cygnet::Mat3gf{}.scale({0.5, 0.5}).translate(body_.pos));
  19. rnd.drawRect(body_.pos, body_.size);
  20. }
  21. void ItemStackEntity::update(const Swan::Context &ctx, float dt) {
  22. physics(ctx, dt, { .mass = MASS, .bounciness = 0.6 });
  23. }
  24. void ItemStackEntity::tick(const Swan::Context &ctx, float dt) {
  25. despawnTimer_ -= dt;
  26. if (despawnTimer_ <= 0)
  27. despawn(ctx);
  28. }
  29. void ItemStackEntity::deserialize(const Swan::Context &ctx, const PackObject &obj) {
  30. body_.pos = obj.at("pos").as<Swan::Vec2>();
  31. item_ = &ctx.world.getItem(obj.at("item").as<std::string>());
  32. }
  33. Swan::Entity::PackObject ItemStackEntity::serialize(const Swan::Context &ctx, msgpack::zone &zone) {
  34. return {
  35. { "pos", msgpack::object(body_.pos, zone) },
  36. { "tile", msgpack::object(item_->name, zone) },
  37. };
  38. }