Player.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include "common/entities/Player.h"
  2. #include "utils/Utils.h"
  3. Player::Player()
  4. : lastLengthAngle(0.0f), lengthAngle(0.0f), lastWidthAngle(0.0f),
  5. widthAngle(0.0f), size(Vector3(0.5f, 1.8f, 0.5f)) {
  6. }
  7. void Player::tick() {
  8. lastPosition = position;
  9. lastLengthAngle = lengthAngle;
  10. lastWidthAngle = widthAngle;
  11. constexpr float drag = 0.48f;
  12. acceleration += Vector3(-velocity[0] * drag, 0.0f, -velocity[2] * drag);
  13. velocity += acceleration;
  14. acceleration = Vector3(0.0f, -0.08f, 0.0f);
  15. }
  16. void Player::addForce(const Vector3& force) {
  17. acceleration += force;
  18. }
  19. const Vector3& Player::getVelocity() const {
  20. return velocity;
  21. }
  22. void Player::move(const Vector3& v) {
  23. position += v;
  24. onGround = v[1] == 0.0f && velocity[1] < 0.0f;
  25. velocity = v;
  26. }
  27. CollisionBox Player::getCollisionBox() const {
  28. return CollisionBox(size).offset(position);
  29. }
  30. bool Player::isOnGround() const {
  31. return onGround;
  32. }
  33. void Player::setPosition(const Vector3& pos) {
  34. setPosition(pos, lengthAngle, widthAngle);
  35. }
  36. void Player::setPosition(const Vector3& pos, float lengthAngle,
  37. float widthAngle) {
  38. Player::lastPosition = pos;
  39. Player::position = pos;
  40. Player::lastLengthAngle = lengthAngle;
  41. Player::lengthAngle = lengthAngle;
  42. Player::lastWidthAngle = widthAngle;
  43. Player::widthAngle = widthAngle;
  44. Player::velocity = Vector3();
  45. Player::acceleration = Vector3();
  46. }
  47. Vector3 Player::getRenderPosition(float lag) const {
  48. return Utils::interpolate(lastPosition, position, lag) +
  49. Vector3(size[0] * 0.5f, size[1], size[2] * 0.5f);
  50. }
  51. Quaternion Player::getRotation() const {
  52. return getRenderRotation(1.0f);
  53. }
  54. Quaternion Player::getRenderRotation(float lag) const {
  55. float lAngle = Utils::interpolate(lastLengthAngle, lengthAngle, lag);
  56. float wAngle = Utils::interpolate(lastWidthAngle, widthAngle, lag);
  57. Quaternion q(Vector3(0.0f, 1.0f, 0.0f), lAngle);
  58. q *= Quaternion(Vector3(1.0f, 0.0f, 0.0f), wAngle);
  59. return q;
  60. }
  61. void Player::addLengthAngle(float angle) {
  62. lengthAngle += angle;
  63. constexpr float full = 360.0f;
  64. while(lengthAngle < 0.0f) {
  65. lengthAngle += full;
  66. lastLengthAngle += full;
  67. }
  68. while(lengthAngle >= full) {
  69. lengthAngle -= full;
  70. lastLengthAngle -= full;
  71. }
  72. }
  73. void Player::addWidthAngle(float angle) {
  74. constexpr float border = 89.9f;
  75. widthAngle += angle;
  76. widthAngle = std::min(std::max(widthAngle + angle, -border), border);
  77. }