Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Character extends Phaser.GameObjects.Sprite {
- constructor (scene, data) {
- super(
- scene,
- scene.positionToRealWorld(data.position.x),
- scene.positionToRealWorld(data.position.y)
- );
- this.scene = scene;
- // eventos
- this.events = {
- startMove: [],
- endMove: [],
- cantMove: []
- };
- this.grassOverlay;
- data = data || {};
- // normaliza dados
- data.position = data.position || {};
- data.position.x = data.position.x || 0;
- data.position.y = data.position.y || 0;
- data.position.facing = data.position.facing || 0;
- data.follower = data.follower || {};
- data.follower.has = data.follower.has || false;
- data.follower.id = data.follower.id || null;
- // aplica dados
- this._data = {
- type: data.type,
- name: data.name,
- sprite: data.sprite,
- atlas: scene.database.characters[data.sprite].atlas,
- position: {
- x: data.position.x,
- y: data.position.y,
- facing: data.position.facing
- },
- stepFlag: 0,
- follower: {
- has: data.follower.has,
- id: data.follower.name
- },
- moveInProgress: false
- };
- if (data.isTamer) {
- this._data.isTamer = true;
- this._data.maxview = data.maxview;
- };
- // seta textura
- this.setTexture(scene.database.characters[data.sprite].atlas);
- this.setFrame(scene.database.characters[data.sprite].name + "_" + this.scene.database.overworld.directions[data.position.facing] + "_idle0");
- // seta posição
- this.setPosition(
- scene.positionToRealWorld(data.position.x),
- scene.positionToRealWorld(data.position.y)
- );
- // seta origem
- const origin = scene.database.characters[data.sprite].origin[this.scene.database.overworld.directions[data.position.facing]];
- this.setOrigin(origin.x, origin.y);
- // adiciona animação de idle
- for (let i = 0, l = scene.database.overworld.directions.length; i < l; i++) {
- // criar animação idle para todos os lados
- scene.anims.create({
- key: scene.database.characters[data.sprite].name + "_idle_" + scene.database.overworld.directions[i],
- frames: [
- {key: scene.database.characters[data.sprite].atlas, frame: scene.database.characters[data.sprite].name + "_" + scene.database.overworld.directions[i] + "_idle0"},
- {key: scene.database.characters[data.sprite].atlas, frame: scene.database.characters[data.sprite].name + "_" + scene.database.overworld.directions[i] + "_idle1"}
- ],
- frameRate: 2,
- repeat: -1
- });
- // adiciona animação a sprite do player
- this.anims.load(scene.database.characters[data.sprite].name + "_idle_" + scene.database.overworld.directions[i]);
- };
- // play na animação idle
- this.anims.play(scene.database.characters[data.sprite].name + "_idle_" + scene.database.overworld.directions[data.position.facing]);
- }
- onStartMove(callback) {
- this.events.startMove.push(callback);
- }
- onEndMove(callback) {
- this.events.endMove.push(callback);
- }
- onCantMove(callback) {
- this.events.cantMove.push(callback);
- }
- triggerStartMove (pos) {
- for (let i = 0, l = this.events.startMove.length; i < l; i++)
- this.events.startMove[i](pos);
- }
- triggerEndMove (pos) {
- for (let i = 0, l = this.events.endMove.length; i < l; i++)
- this.events.endMove[i](pos);
- }
- triggerCantMove (pos) {
- for (let i = 0, l = this.events.cantMove.length; i < l; i++)
- this.events.cantMove[i](pos);
- }
- addInteraction (fn) {
- this.setInteractive().on("pointerdown", fn);
- }
- setFollower (id) {
- this._data.follower = {
- has: true,
- id
- };
- }
- removeFollower () {
- this._data.follower = {
- has: false,
- id: null
- }
- }
- addGrassOverlay (sprite) {
- this.grassOverlay = sprite;
- }
- removeGrassOverlay () {
- if (this.grassOverlay)
- this.grassOverlay.destroy();
- }
- // se mexer no mapa
- move (direction, callback) {
- // se for o jogador
- if (this._data.isPlayer) {
- // se walk estiver em progresso -> sai
- if (this._data.moveInProgress)
- return;
- // se jogador estiver parado -> sai
- if (this._data.stop)
- return;
- };
- // callback interna
- let internal_callback;
- const collision = this.execCollision(direction);
- // vendo quem é
- switch (this._data.type) {
- // se é player
- case 0: {
- switch (collision) {
- // não pode se mover
- case 0: {
- //** publicando no canal do mapa que mudou facing para tal direção
- if (this.scene.subscribe.map.is && this._data.position.facing != direction)
- this.scene.subscribe.map.conn.publish({
- dir: direction,
- dataType: 2
- });
- // mudando facing na memória
- this._data.position.facing = direction;
- // executando animação idle para o lado
- this.anims.play(this.scene.database.characters[this._data.sprite].name + "_idle_" + this.scene.database.overworld.directions[direction]);
- // disparando evento de cant move
- this.triggerCantMove({
- facing: direction,
- x: this._data.position.x,
- y: this._data.position.y
- });
- // saindo pois não ira se mexer
- return;
- };
- // solicitar mudança de mapa
- case 3: {
- // pegando eventos, buscando map id e teleport id
- let teleport = _.findWhere(this.scene.cache.json.get(this.scene.getCurrentMapName("events")).map.teleport, {
- x: this._data.position.x,
- y: this._data.position.y
- }),
- scene = this.scene;
- // adicionar callback e enviar request para o servidor
- internal_callback = function () {
- scene.requestMapChange(teleport.mid, teleport.tid);
- };
- break;
- };
- // solicitar batalha selvagem | criar overlay do matinho
- case 4: {
- let pos = {
- x: this._data.position.x,
- y: this._data.position.y
- },
- self = this;
- // remove grass antigo
- this.removeGrassOverlay();
- // appenda particulas de grama
- internal_callback = function () {
- // adiciona overlay
- self.addGrassOverlay(self.scene.appendGrassOverlay(pos.x, pos.y));
- // add particles
- self.scene.appendGrassParticles(pos.x, pos.y);
- };
- self.requestWildBattle();
- break;
- };
- // checar se tem algum evento
- case 7: {
- // pegando eventos, buscando map id e teleport id
- const
- mapData = this.scene.cache.json.get(this.scene.getCurrentMapName("events")),
- event = _.findWhere(mapData.events.config, {
- x: this._data.position.x,
- y: this._data.position.y
- }),
- self = this;
- internal_callback = function () {
- if (_.indexOf(mapData.events.script[event.id].requiredFlagValueToExec, self.scene.flag) >= 0) {
- self.scene.automatizeAction({
- type: 2
- }, mapData.events.script[event.id].script);
- };
- };
- break;
- };
- };
- //** pode andar
- // setando walk em progresso
- this._data.moveInProgress = true;
- // mudando facing
- this._data.position.facing = direction;
- // parando animação do idle para iniciar animação 'procedural'
- this.anims.stop();
- //** publicando no canal do mapa que andou para tal direção
- if (this.scene.subscribe.map.is)
- this.scene.subscribe.map.conn.publish({
- dir: direction,
- dataType: 1
- });
- if (this._data.follower.has)
- this.scene.follow(older.facing, this._data.follower.id);
- break;
- };
- // se for um jogador online ou um npc, ou um follower, ou npc domador
- case 1:
- case 2:
- case 3:
- case 4:
- {
- // verificando tipo da colisão e execuntando o que deve ser feito
- switch(collision) {
- case 0: {
- // mudando facing
- this._data.position.facing = direction;
- // executando animação idle para o lado
- this.anims.play(this.scene.database.characters[this._data.sprite].name + "_idle_" + this.scene.database.overworld.directions[direction]);
- // saindo
- return;
- };
- case 4: {
- let pos = {
- x: this._data.position.x,
- y: this._data.position.y
- },
- self = this;
- // remove grass antigo
- this.removeGrassOverlay();
- // appenda particulas de grama
- internal_callback = function () {
- // adiciona overlay
- self.addGrassOverlay(self.scene.appendGrassOverlay(pos.x, pos.y));
- // add particles
- self.scene.appendGrassParticles(pos.x, pos.y);
- };
- break;
- };
- };
- // mudando facing
- this._data.position.facing = direction;
- // parando animação do idle para iniciar animação 'procedural'
- this.anims.stop();
- if (this._data.type == 2 || this._data.type == 4) {
- const element = this.scene.cache.json.get(this.scene.getCurrentMapName("events")).elements.config[this._data.name];
- // se mandar salvar a posição dinamica
- if (element.saveDynamicPosition) {
- const el = element[this.scene.flag] || element["default"];
- // preservar a posição do npc
- el.position = {
- x: this._data.position.x,
- y: this._data.position.y,
- facing: this._data.position.facing
- };
- };
- };
- break;
- };
- };
- }
- // mudar facing
- face (direction) {
- // se a direção for se virar ao jogador
- if (direction == "toplayer") {
- // pega qual lado jogar está posicionado
- switch(this.scene.player._data.position.facing) {
- case 0: { // cima
- direction = 2;
- break;
- };
- case 2: { // baixo
- direction = 0;
- break;
- };
- case 3: { // esquerda
- direction = 1;
- break;
- };
- case 1: { // direita
- direction = 3;
- break;
- };
- };
- };
- // mudando facing na memória
- this._data.position.facing = direction;
- // para animação (hack para caso esteja no mesmo lado)
- this.anims.stop();
- // executando animação idle para o lado escolhido
- this.anims.play(this.scene.database.characters[object._data.sprite].name + "_idle_" + this.scene.database.overworld.directions[direction]);
- // se for player publica no mapa q vai virar pra tal direção
- if (this._data.isPlayer && this.scene.subscribe.map.is)
- this.scene.subscribe.map.conn.publish({
- dir: direction,
- dataType: 2
- });
- }
- asyncWalk (direction, internal_callback, callback) {
- async.series([
- next => {
- // disparar evento de start move
- this.triggerStartMove({
- facing: direction,
- x: this._data.position.x,
- y: this._data.position.y
- });
- // mudar origem em relação ao próprio eixo
- this.changeOrigin();
- // tocar flag de step
- this.switchSpriteStep(this._data.stepFlag, "walk");
- // mudar posição
- this.changePositionAsync(direction, next);
- },
- // mudar posição
- next => this.changePositionAsync(direction, next),
- next => {
- // tocar flag de step
- this.switchSpriteStep(0, "idle");
- // mudar posição
- this.changePositionAsync(direction, next);
- },
- // mudar posição
- next => this.changePositionAsync(direction, next)
- ], () => {
- // se for o jogador
- if (this._data.isPlayer)
- this._data.moveInProgress = false;
- this.anims.play(this.scene.database.characters[this._data.sprite].name + "_idle_" + this.scene.database.overworld.directions[direction]);
- // atualizando profundidade dos objetos do grupo main
- this.scene.depthSort();
- // chama callback interno
- if (typeof(this.callback) == "function")
- callback();
- // chama callback externo
- if (typeof(this.internal_callback) == "function")
- internal_callback();
- // triggar end move
- this.triggerEndMove({
- facing: direction,
- x: this._data.position.x,
- y: this._data.position.y
- });
- });
- }
- };
- class Player extends Character {
- constructor (scene, data) {
- super(scene, data);
- this._data.stop = data.stop || false;
- this._data.isPlayer = true;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement