Entity.cpp 2.5 KB

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