Advertisement
nPhoenix

Character Class

Mar 2nd, 2020
2,653
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Character extends Phaser.GameObjects.Sprite {
  2.  
  3.     constructor (scene, data) {
  4.  
  5.         super(
  6.             scene,
  7.             scene.positionToRealWorld(data.position.x),
  8.             scene.positionToRealWorld(data.position.y)
  9.         );
  10.  
  11.         this.scene = scene;
  12.  
  13.         // eventos
  14.         this.events = {
  15.             startMove: [],
  16.             endMove: [],
  17.             cantMove: []
  18.         };
  19.        
  20.         this.grassOverlay;
  21.  
  22.         data = data || {};
  23.         // normaliza dados
  24.         data.position = data.position || {};
  25.         data.position.x = data.position.x || 0;
  26.         data.position.y = data.position.y || 0;
  27.         data.position.facing = data.position.facing || 0;
  28.         data.follower = data.follower || {};
  29.         data.follower.has = data.follower.has || false;
  30.         data.follower.id = data.follower.id || null;
  31.  
  32.         // aplica dados
  33.         this._data = {
  34.             type: data.type,
  35.             name: data.name,
  36.             sprite: data.sprite,
  37.             atlas: scene.database.characters[data.sprite].atlas,
  38.             position: {
  39.                 x: data.position.x,
  40.                 y: data.position.y,
  41.                 facing: data.position.facing
  42.             },
  43.             stepFlag: 0,
  44.             follower: {
  45.                 has: data.follower.has,
  46.                 id: data.follower.name
  47.             },
  48.             moveInProgress: false
  49.         };
  50.  
  51.         if (data.isTamer) {
  52.             this._data.isTamer = true;
  53.             this._data.maxview = data.maxview;
  54.         };
  55.  
  56.         // seta textura
  57.         this.setTexture(scene.database.characters[data.sprite].atlas);
  58.         this.setFrame(scene.database.characters[data.sprite].name + "_" + this.scene.database.overworld.directions[data.position.facing] + "_idle0");
  59.  
  60.         // seta posição
  61.         this.setPosition(
  62.             scene.positionToRealWorld(data.position.x),
  63.             scene.positionToRealWorld(data.position.y)
  64.         );
  65.  
  66.         // seta origem
  67.         const origin = scene.database.characters[data.sprite].origin[this.scene.database.overworld.directions[data.position.facing]];
  68.         this.setOrigin(origin.x, origin.y);
  69.  
  70.         // adiciona animação de idle
  71.         for (let i = 0, l = scene.database.overworld.directions.length; i < l; i++) {
  72.             // criar animação idle para todos os lados
  73.             scene.anims.create({
  74.                 key: scene.database.characters[data.sprite].name + "_idle_" + scene.database.overworld.directions[i],
  75.                 frames: [
  76.                     {key: scene.database.characters[data.sprite].atlas, frame: scene.database.characters[data.sprite].name + "_" + scene.database.overworld.directions[i] + "_idle0"},
  77.                     {key: scene.database.characters[data.sprite].atlas, frame: scene.database.characters[data.sprite].name + "_" + scene.database.overworld.directions[i] + "_idle1"}
  78.                 ],
  79.                 frameRate: 2,
  80.                 repeat: -1
  81.             });
  82.  
  83.             // adiciona animação a sprite do player
  84.             this.anims.load(scene.database.characters[data.sprite].name + "_idle_" + scene.database.overworld.directions[i]);
  85.         };
  86.  
  87.         // play na animação idle
  88.         this.anims.play(scene.database.characters[data.sprite].name + "_idle_" + scene.database.overworld.directions[data.position.facing]);
  89.     }
  90.  
  91.     onStartMove(callback) {
  92.         this.events.startMove.push(callback);
  93.     }
  94.  
  95.     onEndMove(callback) {
  96.         this.events.endMove.push(callback);
  97.     }
  98.  
  99.     onCantMove(callback) {
  100.         this.events.cantMove.push(callback);
  101.     }
  102.  
  103.     triggerStartMove (pos) {
  104.         for (let i = 0, l = this.events.startMove.length; i < l; i++)
  105.             this.events.startMove[i](pos);
  106.     }
  107.  
  108.     triggerEndMove (pos) {
  109.         for (let i = 0, l = this.events.endMove.length; i < l; i++)
  110.             this.events.endMove[i](pos);
  111.     }
  112.  
  113.     triggerCantMove (pos) {
  114.         for (let i = 0, l = this.events.cantMove.length; i < l; i++)
  115.             this.events.cantMove[i](pos);
  116.     }
  117.  
  118.     addInteraction (fn) {
  119.         this.setInteractive().on("pointerdown", fn);
  120.     }
  121.  
  122.     setFollower (id) {
  123.         this._data.follower = {
  124.             has: true,
  125.             id
  126.         };
  127.     }
  128.  
  129.     removeFollower () {
  130.         this._data.follower = {
  131.             has: false,
  132.             id: null
  133.         }
  134.     }
  135.  
  136.     addGrassOverlay (sprite) {
  137.         this.grassOverlay = sprite;
  138.     }
  139.  
  140.     removeGrassOverlay () {
  141.         if (this.grassOverlay)
  142.             this.grassOverlay.destroy();
  143.     }
  144.  
  145.     // se mexer no mapa
  146.     move (direction, callback) {
  147.         // se for o jogador
  148.         if (this._data.isPlayer) {
  149.             // se walk estiver em progresso -> sai
  150.             if (this._data.moveInProgress)
  151.                 return;
  152.  
  153.             // se jogador estiver parado -> sai
  154.             if (this._data.stop)
  155.                 return;
  156.         };
  157.  
  158.         // callback interna
  159.         let internal_callback;
  160.         const collision = this.execCollision(direction);
  161.  
  162.         // vendo quem é
  163.         switch (this._data.type) {
  164.             // se é player
  165.             case 0: {
  166.                 switch (collision) {
  167.  
  168.                     // não pode se mover
  169.                     case 0: {
  170.                         //** publicando no canal do mapa que mudou facing para tal direção
  171.                         if (this.scene.subscribe.map.is && this._data.position.facing != direction)
  172.                             this.scene.subscribe.map.conn.publish({
  173.                                 dir: direction,
  174.                                 dataType: 2
  175.                             });
  176.                         // mudando facing na memória
  177.                         this._data.position.facing = direction;
  178.                         // executando animação idle para o lado
  179.                         this.anims.play(this.scene.database.characters[this._data.sprite].name + "_idle_" + this.scene.database.overworld.directions[direction]);
  180.                         // disparando evento de cant move
  181.                         this.triggerCantMove({
  182.                             facing: direction,
  183.                             x: this._data.position.x,
  184.                             y: this._data.position.y
  185.                         });
  186.                         // saindo pois não ira se mexer
  187.                         return;
  188.                     };
  189.  
  190.                     // solicitar mudança de mapa
  191.                     case 3: {
  192.                         // pegando eventos, buscando map id e teleport id
  193.                         let teleport = _.findWhere(this.scene.cache.json.get(this.scene.getCurrentMapName("events")).map.teleport, {
  194.                                 x: this._data.position.x,
  195.                                 y: this._data.position.y
  196.                             }),
  197.                             scene = this.scene;
  198.  
  199.                         // adicionar callback e enviar request para o servidor
  200.                         internal_callback = function () {
  201.                             scene.requestMapChange(teleport.mid, teleport.tid);
  202.                         };
  203.                         break;
  204.                     };
  205.  
  206.                     // solicitar batalha selvagem | criar overlay do matinho
  207.                     case 4: {
  208.                         let pos = {
  209.                             x: this._data.position.x,
  210.                             y: this._data.position.y
  211.                         },
  212.                             self = this;
  213.                         // remove grass antigo
  214.                         this.removeGrassOverlay();
  215.  
  216.                         // appenda particulas de grama
  217.                         internal_callback = function () {
  218.                             // adiciona overlay
  219.                             self.addGrassOverlay(self.scene.appendGrassOverlay(pos.x, pos.y));
  220.                             // add particles
  221.                             self.scene.appendGrassParticles(pos.x, pos.y);
  222.                         };
  223.  
  224.                         self.requestWildBattle();
  225.                         break;
  226.                     };
  227.  
  228.                     // checar se tem algum evento
  229.                     case 7: {
  230.                         // pegando eventos, buscando map id e teleport id
  231.                         const
  232.                             mapData = this.scene.cache.json.get(this.scene.getCurrentMapName("events")),
  233.                             event = _.findWhere(mapData.events.config, {
  234.                                 x: this._data.position.x,
  235.                                 y: this._data.position.y
  236.                             }),
  237.                             self = this;
  238.  
  239.                         internal_callback = function () {
  240.                             if (_.indexOf(mapData.events.script[event.id].requiredFlagValueToExec, self.scene.flag) >= 0) {
  241.                                 self.scene.automatizeAction({
  242.                                     type: 2
  243.                                 }, mapData.events.script[event.id].script);
  244.                             };
  245.                         };
  246.                         break;
  247.                     };
  248.                 };
  249.  
  250.                 //** pode andar
  251.  
  252.                 // setando walk em progresso
  253.                 this._data.moveInProgress = true;
  254.                 // mudando facing
  255.                 this._data.position.facing = direction;
  256.                 // parando animação do idle para iniciar animação 'procedural'
  257.                 this.anims.stop();
  258.                 //** publicando no canal do mapa que andou para tal direção
  259.                 if (this.scene.subscribe.map.is)
  260.                     this.scene.subscribe.map.conn.publish({
  261.                         dir: direction,
  262.                         dataType: 1
  263.                     });
  264.                 if (this._data.follower.has)
  265.                     this.scene.follow(older.facing, this._data.follower.id);
  266.                 break;
  267.             };
  268.  
  269.             // se for um jogador online ou um npc, ou um follower, ou npc domador
  270.             case 1:
  271.             case 2:
  272.             case 3:
  273.             case 4:
  274.             {
  275.                 // verificando tipo da colisão e execuntando o que deve ser feito
  276.                 switch(collision) {
  277.                     case 0: {
  278.                         // mudando facing
  279.                         this._data.position.facing = direction;
  280.                         // executando animação idle para o lado
  281.                         this.anims.play(this.scene.database.characters[this._data.sprite].name + "_idle_" + this.scene.database.overworld.directions[direction]);
  282.                         // saindo
  283.                         return;
  284.                     };
  285.  
  286.                     case 4: {
  287.                         let pos = {
  288.                             x: this._data.position.x,
  289.                             y: this._data.position.y
  290.                         },
  291.                             self = this;
  292.                         // remove grass antigo
  293.                         this.removeGrassOverlay();
  294.  
  295.                         // appenda particulas de grama
  296.                         internal_callback = function () {
  297.                             // adiciona overlay
  298.                             self.addGrassOverlay(self.scene.appendGrassOverlay(pos.x, pos.y));
  299.                             // add particles
  300.                             self.scene.appendGrassParticles(pos.x, pos.y);
  301.                         };
  302.                         break;
  303.                     };
  304.                 };
  305.  
  306.                 // mudando facing
  307.                 this._data.position.facing = direction;
  308.                 // parando animação do idle para iniciar animação 'procedural'
  309.                 this.anims.stop();
  310.  
  311.                 if (this._data.type == 2 || this._data.type == 4) {
  312.  
  313.                     const element = this.scene.cache.json.get(this.scene.getCurrentMapName("events")).elements.config[this._data.name];
  314.  
  315.                     // se mandar salvar a posição dinamica
  316.                     if (element.saveDynamicPosition) {
  317.                         const el = element[this.scene.flag] || element["default"];
  318.                         // preservar a posição do npc
  319.                         el.position = {
  320.                             x: this._data.position.x,
  321.                             y: this._data.position.y,
  322.                             facing: this._data.position.facing
  323.                         };
  324.                     };
  325.                 };
  326.                 break;
  327.             };
  328.         };
  329.     }
  330.  
  331.     // mudar facing
  332.     face (direction) {
  333.         // se a direção for se virar ao jogador
  334.         if (direction == "toplayer") {
  335.             // pega qual lado jogar está posicionado
  336.             switch(this.scene.player._data.position.facing) {
  337.                 case 0: { // cima
  338.                     direction = 2;
  339.                     break;
  340.                 };
  341.                 case 2: {  // baixo
  342.                     direction = 0;
  343.                     break;
  344.                 };
  345.                 case 3: { // esquerda
  346.                     direction = 1;
  347.                     break;
  348.                 };
  349.                 case 1: { // direita
  350.                     direction = 3;
  351.                     break;
  352.                 };
  353.             };
  354.         };
  355.  
  356.         // mudando facing na memória
  357.         this._data.position.facing = direction;
  358.         // para animação (hack para caso esteja no mesmo lado)
  359.         this.anims.stop();
  360.         // executando animação idle para o lado escolhido
  361.         this.anims.play(this.scene.database.characters[object._data.sprite].name + "_idle_" + this.scene.database.overworld.directions[direction]);
  362.         // se for player publica no mapa q vai virar pra tal direção
  363.         if (this._data.isPlayer && this.scene.subscribe.map.is)
  364.             this.scene.subscribe.map.conn.publish({
  365.                 dir: direction,
  366.                 dataType: 2
  367.             });
  368.     }
  369.  
  370.     asyncWalk (direction, internal_callback, callback) {
  371.         async.series([
  372.             next => {
  373.                 // disparar evento de start move
  374.                 this.triggerStartMove({
  375.                     facing: direction,
  376.                     x: this._data.position.x,
  377.                     y: this._data.position.y
  378.                 });
  379.                 // mudar origem em relação ao próprio eixo
  380.                 this.changeOrigin();
  381.                 // tocar flag de step
  382.                 this.switchSpriteStep(this._data.stepFlag, "walk");
  383.                 // mudar posição
  384.                 this.changePositionAsync(direction, next);
  385.             },
  386.             // mudar posição
  387.             next => this.changePositionAsync(direction, next),
  388.             next => {
  389.                 // tocar flag de step
  390.                 this.switchSpriteStep(0, "idle");
  391.                 // mudar posição
  392.                 this.changePositionAsync(direction, next);
  393.             },
  394.             // mudar posição
  395.             next => this.changePositionAsync(direction, next)
  396.         ], () => {
  397.  
  398.         // se for o jogador
  399.         if (this._data.isPlayer)
  400.             this._data.moveInProgress = false;
  401.  
  402.         this.anims.play(this.scene.database.characters[this._data.sprite].name + "_idle_" + this.scene.database.overworld.directions[direction]);
  403.  
  404.         // atualizando profundidade dos objetos do grupo main
  405.         this.scene.depthSort();
  406.  
  407.         // chama callback interno
  408.         if (typeof(this.callback) == "function")
  409.             callback();
  410.  
  411.         // chama callback externo
  412.         if (typeof(this.internal_callback) == "function")
  413.             internal_callback();
  414.  
  415.         // triggar end move
  416.         this.triggerEndMove({
  417.             facing: direction,
  418.             x: this._data.position.x,
  419.             y: this._data.position.y
  420.         });
  421.         });
  422.     }
  423. };
  424.  
  425. class Player extends Character {
  426.     constructor (scene, data) {
  427.         super(scene, data);
  428.         this._data.stop = data.stop || false;
  429.         this._data.isPlayer = true;
  430.     }
  431. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement