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.

Entity.h 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #pragma once
  2. #include <memory>
  3. #include <optional>
  4. #include <msgpack.hpp>
  5. #include "common.h"
  6. #include "log.h"
  7. #include "traits/BodyTrait.h"
  8. #include "traits/PhysicsTrait.h"
  9. namespace Swan {
  10. class World;
  11. class WorldPlane;
  12. class Game;
  13. class Entity: NonCopyable {
  14. public:
  15. using PackObject = std::unordered_map<std::string_view, msgpack::object>;
  16. struct Factory {
  17. const std::string name;
  18. std::unique_ptr<Entity> (*create)(const Context &ctx, const PackObject &obj);
  19. };
  20. Entity() = default;
  21. Entity(Entity &&) = default;
  22. virtual ~Entity() = default;
  23. Entity &operator=(Entity &&) = default;
  24. void despawn(const Swan::Context &ctx);
  25. virtual void draw(const Context &ctx, Cygnet::Renderer &rnd) {}
  26. virtual void update(const Context &ctx, float dt) {}
  27. virtual void tick(const Context &ctx, float dt) {}
  28. virtual void onDespawn(const Context &ctx) {}
  29. virtual void deserialize(const Swan::Context &ctx, const PackObject &obj) {}
  30. virtual PackObject serialize(const Swan::Context &ctx, msgpack::zone &zone) { return {}; }
  31. size_t index_;
  32. size_t generation_;
  33. };
  34. class PhysicsEntity: public Entity, public BodyTrait, public PhysicsTrait {
  35. public:
  36. PhysicsEntity(Vec2 size): body_({ .size = size }) {}
  37. BodyTrait::Body &get(BodyTrait::Tag) override { return body_; }
  38. PhysicsTrait::Physics &get(PhysicsTrait::Tag) override { return physics_; }
  39. void physics(
  40. const Context &ctx, float dt,
  41. const BasicPhysics::Props &props) {
  42. physics_.standardForces(props.mass);
  43. physics_.update(ctx, dt, body_, props);
  44. }
  45. protected:
  46. BodyTrait::Body body_;
  47. BasicPhysics physics_;
  48. };
  49. }