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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. if (!this.onGround)
  42. this.relVelocity.y += this.gravity * dt;
  43. // If we just started riding something, adjust relative velocity
  44. if (!this.prevRelativeTo && this.relativeTo) {
  45. this.relVelocity.x = this.velocity.x - this.relativeTo.velocity.x;
  46. this.relVelocity.y = this.velocity.y - this.relativeTo.velocity.y;
  47. // If we just stopped riding something, adjust relative velocity
  48. } else if (this.prevRelativeTo && !this.relativeTo) {
  49. this.relVelocity.x = this.velocity.x + this.relativeTo.velocity.x;
  50. this.relVelocity.y = this.velocity.y + this.relativeTo.velocity.y;
  51. }
  52. // Apply friction
  53. var fric = this.onGround ? this.groundFriction : this.airFriction;
  54. var xRatio = 1 / (1 + (dt * fric));
  55. this.relVelocity.x *= xRatio;
  56. // Update velocity
  57. if (this.relativeTo) {
  58. this.velocity.x = this.relVelocity.x + this.relativeTo.velocity.x;
  59. this.velocity.y = this.relVelocity.y + this.relativeTo.velocity.y;
  60. } else {
  61. this.velocity.x = this.relVelocity.x;
  62. this.velocity.y = this.relVelocity.y;
  63. }
  64. }
  65. postUpdate(dt) {
  66. this.entity.bounds.pos.x += this.velocity.x * dt;
  67. this.entity.bounds.pos.y += this.velocity.y * dt;
  68. }
  69. }