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.

BrokenPlatform.js 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import Entity from "../Entity.js";
  2. import {Trait} from "../Entity.js";
  3. import Texture from "../Texture.js";
  4. import Tile from "../Tile.js";
  5. import Shaker from "../Shaker.js";
  6. import Vec2 from "../Vec2.js";
  7. import assets from "../assets.js";
  8. import TPlatform from "../traits/TPlatform.js";
  9. import TCollider from "../traits/TCollider.js";
  10. import TPhysics from "../traits/TPhysics.js";
  11. class Behavior extends Trait {
  12. constructor(entity) {
  13. super(entity, "behavior");
  14. this.shaker = new Shaker();
  15. this.shake = 0;
  16. this.shakeAccel = 14;
  17. this.reliableTime = 1;
  18. this.resetTime = 4;
  19. this.state = 0;
  20. this.timer = 0;
  21. }
  22. init() {
  23. this.initialPos = this.entity.pos.clone();
  24. this.entity.t.physics.enabled = false;
  25. }
  26. reset() {
  27. this.entity.t.physics.enabled = false;
  28. this.shake = 0;
  29. this.entity.t.physics.velocity.set(0, 0);
  30. this.entity.pos.set(this.initialPos.x, this.initialPos.y);
  31. this.state = 0;
  32. this.timer = 0;
  33. }
  34. update(dt) {
  35. if (this.state === 0) {
  36. this.entity.t.collider.entities.forEach(e => {
  37. let fall =
  38. e.has("physics") &&
  39. e.bounds.intersectSide(this.entity.bounds) === "top";
  40. if (fall) {
  41. this.timer = this.reliableTime;
  42. this.state = 1;
  43. }
  44. });
  45. }
  46. if (this.state === 1) {
  47. this.shaker.shake(this.shake);
  48. this.shake += this.shakeAccel * dt;
  49. this.timer -= dt;
  50. if (this.timer <= 0) {
  51. this.entity.t.physics.enabled = true;
  52. this.state = 2;
  53. this.timer = this.resetTime;
  54. }
  55. } else if (this.state === 2) {
  56. this.timer -= dt;
  57. if (this.timer <= 0) {
  58. this.reset();
  59. }
  60. }
  61. this.shaker.update(dt);
  62. }
  63. }
  64. export default class BrokenPlatform extends Entity {
  65. constructor(level, width = 5) {
  66. super(level, "platform");
  67. this.bounds.size.set(width, 0.5);
  68. this.addTrait(new TCollider(this));
  69. this.addTrait(new TPlatform(this));
  70. this.addTrait(new TPhysics(this));
  71. this.addTrait(new Behavior(this));
  72. this.texture = new Texture(assets.tiles, Tile.createLine(
  73. Vec2.zero, this.bounds.size.x,
  74. "broken-platform"));
  75. }
  76. draw(ctx) {
  77. let shaker = this.t.behavior.shaker;
  78. this.texture.draw(
  79. ctx,
  80. this.pos.pixelX + shaker.vec.pixelX,
  81. this.pos.pixelY + shaker.vec.pixelY);
  82. }
  83. }