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.

TPhysics.js 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import {Trait} from "../Entity.js";
  2. import Vec2 from "../Vec2.js";
  3. export default class TPhysics extends Trait {
  4. constructor(entity) {
  5. super(entity, "physics");
  6. this.gravity = 40;
  7. this.groundFriction = 6;
  8. this.airFriction = 2;
  9. this.velocity = new Vec2();
  10. this.relVelocity = new Vec2();
  11. this.onGround = false;
  12. this.prevRelativeTo = null;
  13. this.relativeTo = null;
  14. }
  15. update(dt) {
  16. let collider = this.entity.t.collider;
  17. this.prevRelativeTo = this.relativeTo;
  18. this.relativeTo = null;
  19. this.onGround = false;
  20. if (
  21. this.entity.has("collider") &&
  22. collider.collides &&
  23. this.relVelocity.y >= 0) {
  24. // Structures are static; just teleport us to the top of them
  25. if (collider.cStructure) {
  26. this.relVelocity.y = 0;
  27. this.entity.bounds.bottom = collider.cStructure.top;
  28. this.onGround = true;
  29. // If we're colliding with an entity, and that entity is
  30. // a platform, teleport us to the top of them.
  31. } else if (collider.cEntity.has("platform")) {
  32. this.relVelocity.y = 0;
  33. this.entity.bounds.bottom = collider.cEntity.bounds.top;
  34. this.onGround = true;
  35. if (collider.cEntity.has("physics")) {
  36. let cPhys = collider.cEntity.t.physics;
  37. this.relativeTo = cPhys;
  38. }
  39. }
  40. }
  41. this.relVelocity.y += this.gravity * dt;
  42. // If we just started riding something, adjust relative velocity
  43. if (!this.prevRelativeTo && this.relativeTo) {
  44. this.relVelocity.x = this.velocity.x - this.relativeTo.velocity.x;
  45. this.relVelocity.y = this.velocity.y - this.relativeTo.velocity.y;
  46. // If we just stopped riding something, adjust relative velocity
  47. } else if (this.prevRelativeTo && !this.relativeTo) {
  48. this.relVelocity.x = this.velocity.x + this.relativeTo.velocity.x;
  49. this.relVelocity.y = this.velocity.y + this.relativeTo.velocity.y;
  50. }
  51. // Apply friction
  52. var fric = this.onGround ? this.groundFriction : this.airFriction;
  53. var xRatio = 1 / (1 + (dt * fric));
  54. this.relVelocity.x *= xRatio;
  55. // Update velocity
  56. if (this.relativeTo) {
  57. this.velocity.x = this.relVelocity.x + this.relativeTo.velocity.x;
  58. this.velocity.y = this.relVelocity.y + this.relativeTo.velocity.y;
  59. } else {
  60. this.velocity.x = this.relVelocity.x;
  61. this.velocity.y = this.relVelocity.y;
  62. }
  63. }
  64. postUpdate(dt) {
  65. this.entity.bounds.pos.x += this.velocity.x * dt;
  66. this.entity.bounds.pos.y += this.velocity.y * dt;
  67. }
  68. }