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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import {Trait} from "../Entity.js";
  2. import Vec2 from "../Vec2.js";
  3. let zeroVector = new Vec2(0, 0);
  4. export default class TPhysics extends Trait {
  5. constructor(entity) {
  6. super(entity, "physics");
  7. this.velocity = new Vec2();
  8. this.gravity = 40;
  9. this.groundFriction = 6;
  10. this.airFriction = 2;
  11. this.timeLastOnGround = 0;
  12. this.onGround = false;
  13. this.groundBounds = null;
  14. this.groundVelocity = null;
  15. }
  16. collideTop(bounds, velocity) {
  17. if (!this.groundBounds || bounds.top < this.groundBounds.top) {
  18. this.groundBounds = bounds;
  19. this.groundVelocity = velocity;
  20. }
  21. }
  22. collideWall(bounds, velocity) {
  23. let side = this.entity.bounds.intersectSide(bounds);
  24. if (side === "top")
  25. return this.collideTop(bounds, velocity);
  26. }
  27. collidePlatform(bounds, velocity) {
  28. let side = this.entity.bounds.intersectSide(bounds);
  29. if (side === "top")
  30. return this.collideTop(bounds, velocity);
  31. }
  32. update(dt) {
  33. // Collide
  34. if (this.entity.has("collider")) {
  35. let collider = this.entity.t.collider;
  36. this.groundBounds = null;
  37. this.groundVelocity = null;
  38. collider.entities.forEach(e => {
  39. let vel = zeroVector;
  40. if (e.has("physics"))
  41. vel = e.t.physics.velocity;
  42. if (e.has("wall"))
  43. this.collideWall(e.bounds, vel);
  44. else if (e.has("platform"))
  45. this.collidePlatform(e.bounds, vel);
  46. });
  47. collider.structures.forEach((s, i) => {
  48. let bounds = collider.structureBounds[i];
  49. if (s.attrs.wall)
  50. this.collideWall(bounds, zeroVector);
  51. else if (s.attrs.platform)
  52. this.collidePlatform(bounds, zeroVector);
  53. });
  54. }
  55. this.onGround =
  56. (this.groundVelocity && this.velocity.y >= this.groundVelocity.y);
  57. if (this.onGround) {
  58. this.timeLastOnGround = this.entity.time;
  59. this.velocity.y = this.groundVelocity.y;
  60. }
  61. if (!this.onGround)
  62. this.velocity.y += this.gravity * dt;
  63. // Apply friction
  64. var fric = this.onGround ? this.groundFriction : this.airFriction;
  65. var xRatio = 1 / (1 + (dt * fric));
  66. this.velocity.x *= xRatio;
  67. }
  68. postUpdate(dt) {
  69. // Move
  70. this.entity.bounds.pos.x += this.velocity.x * dt;
  71. this.entity.bounds.pos.y += this.velocity.y * dt;
  72. if (this.onGround)
  73. this.entity.bounds.bottom = this.groundBounds.top;
  74. }
  75. }