A 2D tile-based sandbox game.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

PlayerEntity.cc 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include "PlayerEntity.h"
  2. #include <cmath>
  3. #include "ItemStackEntity.h"
  4. PlayerEntity::PlayerEntity(const Swan::Context &ctx, Swan::Vec2 pos):
  5. PlayerEntity(ctx) {
  6. body_.pos = pos;
  7. }
  8. PlayerEntity::PlayerEntity(const Swan::Context &ctx, const PackObject &obj):
  9. PlayerEntity(ctx) {
  10. deserialize(ctx, obj);
  11. }
  12. void PlayerEntity::draw(const Swan::Context &ctx, Swan::Win &win) {
  13. body_.outline(win);
  14. anims_[(int)state_].draw(body_.pos - Swan::Vec2(0.2, 0.1), win);
  15. }
  16. void PlayerEntity::update(const Swan::Context &ctx, float dt) {
  17. State oldState = state_;
  18. state_ = State::IDLE;
  19. mouse_tile_ = ctx.game.getMouseTile();
  20. ctx.plane.debugBox(mouse_tile_);
  21. jump_timer_.tick(dt);
  22. // Break block
  23. if (ctx.game.isMousePressed(SDL_BUTTON_LEFT))
  24. ctx.plane.breakTile(mouse_tile_);
  25. // Move left
  26. if (ctx.game.isKeyPressed(SDL_SCANCODE_A) || ctx.game.isKeyPressed(SDL_SCANCODE_LEFT)) {
  27. physics_.force += Swan::Vec2(-MOVE_FORCE, 0);
  28. state_ = State::RUNNING_L;
  29. }
  30. // Move right
  31. if (ctx.game.isKeyPressed(SDL_SCANCODE_D) || ctx.game.isKeyPressed(SDL_SCANCODE_RIGHT)) {
  32. physics_.force += Swan::Vec2(MOVE_FORCE, 0);
  33. if (state_ == State::RUNNING_L)
  34. state_ = State::IDLE;
  35. else
  36. state_ = State::RUNNING_R;
  37. }
  38. bool jump_pressed = ctx.game.isKeyPressed(SDL_SCANCODE_SPACE);
  39. // Jump
  40. if (physics_.on_ground && jump_pressed && jump_timer_.periodic(0.5)) {
  41. physics_.vel.y = -JUMP_VEL;
  42. }
  43. // Fall down faster than we went up
  44. if (!physics_.on_ground && (!jump_pressed || physics_.vel.y > 0))
  45. physics_.force += Swan::Vec2(0, DOWN_FORCE);
  46. if (state_ != oldState)
  47. anims_[(int)state_].reset();
  48. anims_[(int)state_].tick(dt);
  49. physics(ctx, dt, { .mass = MASS });
  50. }
  51. void PlayerEntity::tick(const Swan::Context &ctx, float dt) {
  52. for (ItemStackEntity *ent: ctx.plane.getEntsOfType<ItemStackEntity>()) {
  53. float squared_dist =
  54. (body_.bottomMid() - ent->get(Swan::BodyTrait::Tag{}).center())
  55. .squareLength();
  56. if (squared_dist < 0.5 * 0.5) {
  57. // TODO: Pick up
  58. }
  59. }
  60. }
  61. void PlayerEntity::deserialize(const Swan::Context &ctx, const PackObject &obj) {
  62. //body_.deserialize(obj["body"]);
  63. }
  64. Swan::Entity::PackObject PlayerEntity::serialize(const Swan::Context &ctx, msgpack::zone &zone) {
  65. return {};
  66. /*
  67. return Swan::MsgPackObject{
  68. { "body", body_.serialize(w) },
  69. };
  70. */
  71. }