Guest User

Untitled

a guest
Jan 20th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. // We define a Component, just a regular class with some data, no functions!
  2. class PositionComponent {
  3. constructor(canMove, pos = {}){
  4. this.canMove = canMove;
  5. this.pos = {
  6. x: pos.x,
  7. y: pos.y
  8. };
  9. this.dest = {
  10. x: pos.x,
  11. y: pos.y
  12. };
  13. }
  14. }
  15.  
  16. // An entity is just an object with Components
  17. let entity = {
  18. 'POS_COMP': new PositionComponent(true, {x: 10, y: 20})
  19. };
  20.  
  21. // An array of entities which we can easily extend
  22. let entities = [entity];
  23.  
  24.  
  25. // A move system
  26. function moveSystem(entities){
  27. entities.forEach((entity) => {
  28.  
  29. // only if a POS_COMP exists, else we do nothing
  30. if (entity.POS_COMP) {
  31. let distX = entity.POS_COMP.dest.x - entity.POS_COMP.pos.x;
  32. let distY = entity.POS_COMP.dest.y - entity.POS_COMP.pos.y;
  33.  
  34. if (distX > 0) {
  35. entity.POS_COMP.pos.x = Math.min(entity.POS_COMP.dest.x, entity.POS_COMP.pos.x + 1);
  36. } else {
  37. entity.POS_COMP.pos.x = Math.max(entity.POS_COMP.dest.x, entity.POS_COMP.pos.x - 1);
  38. }
  39.  
  40. if (distY > 0) {
  41. entity.POS_COMP.pos.y = Math.min(entity.POS_COMP.dest.y, entity.POS_COMP.pos.y + 1);
  42. } else {
  43. entity.POS_COMP.pos.y = Math.max(entity.POS_COMP.dest.y, entity.POS_COMP.pos.y - 1);
  44. }
  45. }
  46. });
  47. }
  48.  
  49. // We loop over the system every second, trying to perform some logic
  50. setInterval(() => {
  51. moveSystem(entities);
  52. }, 1000);
Add Comment
Please, Sign In to add comment