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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include "EntPlayer.h"
  2. EntPlayer::EntPlayer(const Swan::Context &ctx, const Swan::Vec2 &pos):
  3. body_(pos, SIZE, MASS) {
  4. anims_[(int)State::IDLE].init(32, 64, 0.8,
  5. ctx.world.getAsset("core::player-still"));
  6. anims_[(int)State::RUNNING_R].init(32, 64, 1,
  7. ctx.world.getAsset("core::player-running"));
  8. anims_[(int)State::RUNNING_L].init(32, 64, 1,
  9. ctx.world.getAsset("core::player-running"), (int)Swan::Animation::Flags::HFLIP);
  10. }
  11. void EntPlayer::draw(const Swan::Context &ctx, Swan::Win &win) {
  12. body_.outline(win);
  13. win.setPos(body_.pos_ - Swan::Vec2(0.2, 0.1));
  14. anims_[(int)state_].draw(win);
  15. }
  16. void EntPlayer::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(sf::Mouse::Button::Left))
  24. ctx.plane.setTile(mouse_tile_, "core::air");
  25. // Move left
  26. if (ctx.game.isKeyPressed(sf::Keyboard::A) || ctx.game.isKeyPressed(sf::Keyboard::Left)) {
  27. body_.force_ += Swan::Vec2(-FORCE, 0);
  28. state_ = State::RUNNING_L;
  29. }
  30. // Move right
  31. if (ctx.game.isKeyPressed(sf::Keyboard::D) || ctx.game.isKeyPressed(sf::Keyboard::Right)) {
  32. body_.force_ += Swan::Vec2(FORCE, 0);
  33. if (state_ == State::RUNNING_L)
  34. state_ = State::IDLE;
  35. else
  36. state_ = State::RUNNING_R;
  37. }
  38. // Jump
  39. if (body_.on_ground_ && ctx.game.isKeyPressed(sf::Keyboard::Space) && jump_timer_.periodic(0.5)) {
  40. body_.vel_.y_ = -JUMP_FORCE;
  41. }
  42. if (state_ != oldState)
  43. anims_[(int)state_].reset();
  44. anims_[(int)state_].tick(dt);
  45. body_.friction(FRICTION);
  46. body_.gravity();
  47. body_.update(dt);
  48. body_.collide(ctx.plane);
  49. }