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.

EntPlayer.cc 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include "EntPlayer.h"
  2. EntPlayer::EntPlayer(const Swan::Context &ctx, const Swan::SRF &params):
  3. PhysicsEntity(SIZE, MASS),
  4. anims_{
  5. Swan::Animation(ctx.resources.getImage("core::player-still"), 0.8),
  6. Swan::Animation(ctx.resources.getImage("core::player-running"), 1),
  7. Swan::Animation(ctx.resources.getImage("core::player-running"), 1, Swan::Animation::Flags::HFLIP) } {
  8. readSRF(ctx, params);
  9. }
  10. void EntPlayer::draw(const Swan::Context &ctx, Swan::Win &win) {
  11. body_.outline(win);
  12. win.setPos(body_.pos_ - Swan::Vec2(0.2, 0.1));
  13. anims_[(int)state_].draw(win);
  14. }
  15. void EntPlayer::update(const Swan::Context &ctx, float dt) {
  16. State oldState = state_;
  17. state_ = State::IDLE;
  18. mouse_tile_ = ctx.game.getMouseTile();
  19. ctx.plane.debugBox(mouse_tile_);
  20. jump_timer_.tick(dt);
  21. // Break block
  22. if (ctx.game.isMousePressed(SDL_BUTTON_LEFT))
  23. ctx.plane.breakBlock(mouse_tile_);
  24. // Move left
  25. if (ctx.game.isKeyPressed(SDL_SCANCODE_A) || ctx.game.isKeyPressed(SDL_SCANCODE_LEFT)) {
  26. body_.force_ += Swan::Vec2(-FORCE, 0);
  27. state_ = State::RUNNING_L;
  28. }
  29. // Move right
  30. if (ctx.game.isKeyPressed(SDL_SCANCODE_D) || ctx.game.isKeyPressed(SDL_SCANCODE_RIGHT)) {
  31. body_.force_ += Swan::Vec2(FORCE, 0);
  32. if (state_ == State::RUNNING_L)
  33. state_ = State::IDLE;
  34. else
  35. state_ = State::RUNNING_R;
  36. }
  37. // Jump
  38. if (body_.on_ground_ && ctx.game.isKeyPressed(SDL_SCANCODE_SPACE) && jump_timer_.periodic(0.5)) {
  39. body_.vel_.y = -JUMP_FORCE;
  40. }
  41. if (state_ != oldState)
  42. anims_[(int)state_].reset();
  43. anims_[(int)state_].tick(dt);
  44. Swan::PhysicsEntity::update(ctx, dt);
  45. }
  46. void EntPlayer::readSRF(const Swan::Context &ctx, const Swan::SRF &srf) {
  47. auto pos = dynamic_cast<const Swan::SRFFloatArray &>(srf);
  48. body_.pos_.set(pos.val[0], pos.val[1]);
  49. }
  50. Swan::SRF *EntPlayer::writeSRF(const Swan::Context &ctx) {
  51. return new Swan::SRFFloatArray{ body_.pos_.x, body_.pos_.y };
  52. }