-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathnpc.js
More file actions
1196 lines (950 loc) · 49 KB
/
npc.js
File metadata and controls
1196 lines (950 loc) · 49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*This software is released under MIT License. Texts for license are listed below:
* Aventura do Saber , a educational fantasy action RPG
* Copyright (c) 2012-2013, ITSimples Games
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
----------------------------------
Ficheiro: npc.js
ClassName:npc
Comment: Non players charters
Create Date: 17/07/2012 - ITSimples
HTTP://www.itsimples.com
-----------------------------------
*/
// *************************
// **** NPC entity ****
// *************************
var NpcEntity = me.ObjectEntity.extend({
//Construtor:
//Construtor:
init : function(x, y, settings, npcData) {
// Chamar o contrutor
this.parent(x, y, settings);
// NPC data from json file
this.npcData = npcData;
// Data to message box
this.msgData = {};
this.msgData.msgImage = 'sprites/' + this.npcData.imagem.replace(".png", "_face.png");
this.msgData.msgName = this.npcData.nome;
this.msgData.msg = language.npcs[this.npcData.mensagem[2]];
this.collidable = true;
this.gravity = 0;
this.friction = 0;
//Diferrence between npc height and tilesize to avoid collision with wall
this.avoidWall = (this.npcData.tamanhoImagem.altura - ads_tile_size) + 1;
// console.log("this.avoidWall:", this.avoidWall);
// Config NPC acceleration
this.accel.x = this.accel.y = this.npcData.velocidade;
//Set animation speed
this.animationspeed = me.sys.fps / (me.sys.fps / 3);
if (typeof this.npcData.areaColisao !== "undefined"){
var xOffset = this.npcData.areaColisao.x ; // x offset (-1 don't change the with)
var widthHitBox = this.npcData.areaColisao.w ; // width of the hit box
var yOffset = this.npcData.areaColisao.y ; // y offset (-1 don't change the height)
var heightHitBox = this.npcData.areaColisao.h ; // height of the hit box
// adjust the bounding box
this.updateColRect(xOffset,widthHitBox,yOffset,heightHitBox);
}
// adjust the bounding box
// this.updateColRect(0,32,19,20);
// make him start from the right
this.pos.x = x;
this.pos.y = y;
// Set NPC object type
this.type = 'NPC_OBJECT';
// Enable/disable dialogue box
// this.showMessage = false;
//Keep animations data
this.animation = {};
//Standard animations or animation defined on json npc data
if ( this.npcData.animacoes === undefined ){
// Standard animation for all NPC's
this.animation = {"stand-down" : [4],
"stand-left" : [8],
"stand-up" : [1],
"stand-right" : [11],
"down" : [3, 4, 5, 4],
"left" : [6, 7, 8],
"up" : [0, 1, 2, 1],
"right" : [9, 10, 11]
};
}else{
// Animation defined on json
this.animation = this.npcData.animacoes;
}
// To use in each loop
var self = this;
//If there is a first animation for prisoner when is not free and it's stoped first time
if ( this.npcData.animacoes !== undefined && this.npcData.animacoes.primeiraAnimacao !== undefined ){
this.firstAnimation = true;
}else{
this.firstAnimation =false;
}
// console.log('NPC Name:', this.npcData.nome , '- this.firstAnimation:' , this.firstAnimation );
// Add all animation for NPC
var countAnimation = 0;
$.each ( this.animation, function (i, npcAnimation ){
// console.log('npcAnimation:', i , '-' , npcAnimation );
self.renderable.addAnimation( i , npcAnimation );
countAnimation++;
});
// console.log("NPC:" , this.npcData.nome , " this.firstAnimation:" , this.firstAnimation);
//Configurar animações
// this.addAnimation("stand-down", [4]);
// this.addAnimation("stand-left", [8]);
// this.addAnimation("stand-up", [1]);
// this.addAnimation("stand-right", [11]);
// this.addAnimation("down", [3, 4, 5, 4]);
// this.addAnimation("left", [6, 7, 8]);
// this.addAnimation("up", [0, 1, 2, 1]);
// this.addAnimation("right", [9, 10, 11]);
// Make animation to die
// Json "morre" : {"animacao" : [12] },
// if (this.npcData.categoria == "enemies") {
// this.addAnimation("die", this.npcData.morre.animacao);
// }
// Check if this npc is a prisoner
this.prisoner = this.npcData.prisioneiro;
// Create message box for object to avoid blinking if is a global box
this.message = new adsGame.Message();
//To store the distances bewwen two start and end point
this.distanceX = 0;
this.distanceY = 0;
// If NPC reaches the end stops
this.stop = false;
//Get the path from Astar algotithm from pathfinder.js
this.path = [[]];
//Get the path from Astar algotithm from pathfinder.js
this.heroFollowPath = [[]];
//Get reverse path from Astar algotithm from pathfinder.js
// this.reversePath = [[]];
this.reversePathNumber = -1;
// Save path when reverse is used
this.cachepath = [[]];
//Number of points in the path
this.countPath = 0;
//Next destination of the NPC
this.destX = 0;
this.destY = 0;
//Set initial direction of NPC
this.direction = "down";
//Current path
this.currentPath = 0;
//Event wait time
this.waitEvent = 0;
//Use this variable to read waitEvent only one time
this.readOneTimeEvent = false;
//Increment number of events
this.CurrentEventNumber = 0;
// Check if event is happening at the moment
this.eventHappening = false;
// Check if event talk is happening at the moment
this.talkEventHappening = false;
//Testing if NPC should change is direction when collide with hero
this.changeNPCDirection = true;
// To test if is hero that collide with npc or the opposite
this.heroChangeDirection = false;
// Save initial Z index for this object
this.initialZIndex = this.z;
// Set variable to see if NPC is collide with NPC
this.collideHero = false;
this.npcEvents = this.npcData.evento;
this.npcEscapeEvents = this.npcData.eventoFuga;
// Initialize hello sound
this.helloSound = false;
// this.npcData.tipoMovimento = "path";
// console.log("this.npcData.tipoMovimento:", this.npcData.tipoMovimento);
//Check NPC movement
if (this.npcData.tipoMovimento == "path") {
// Get start and end position from gamedata.json for all paths
for ( var pathNumber = 0; pathNumber < this.npcData.coordenadas.length; pathNumber++) {
var start = [this.npcData.coordenadas[pathNumber].initStartX, this.npcData.coordenadas[pathNumber].initStartY];
var end = [this.npcData.coordenadas[pathNumber].initDestX, this.npcData.coordenadas[pathNumber].initDestY];
// Calculate path
// this.path[pathNumber] = adsGame.pathFinder.getPath(start,end,"collision");
this.path[pathNumber] = adsGame.pathFinder.getPath(start, end);
// Calculate reverse path if event reverse
if (this.npcData.coordenadas[pathNumber].reverter) {
// this.reversePath[pathNumber] = adsGame.pathFinder.getPath(end,start,"collision");
this.reversePathNumber = pathNumber;
// console.log('Calculate reverse path...' , pathNumber);
// // Keep a cache of normal path...
// this.cachepath[this.currentPath] = this.path[this.currentPath];
}
}
//*ads_tile_size to convert tile position to map coordinates
// First destination on array path
this.destX = this.path[0][0][0] * ads_tile_size;
this.destY = (this.path[0][0][1] * ads_tile_size) - this.avoidWall;
} else if (this.npcData.tipoMovimento == "circle") {
} else {
//*ads_tile_size to convert tile position to map coordinates
// If NPC movement is between two points only
this.destX = this.npcData.coordenadas[0].initDestX * ads_tile_size;
this.destY = (this.npcData.coordenadas[0].initDestY * ads_tile_size) - this.avoidWall;
}
// *****************************************************
// ** Testing dragon fire breath
// *****************************************************
if (this.npcData.categoria == "enemies") {
if (this.npcData.ataca) {
var npcThrower = this.npcData.nomeAtirador;
this.throwerData = throwersData[npcThrower];
this.thrower = new throwersEntity((this.pos.x + 24) * ads_tile_size, (this.pos.y + 20) * ads_tile_size, this.throwerData);
me.game.add(this.thrower, 6);
me.game.sort.defer();
}
// Initial live for NPC
this.health = this.npcData.vida;
//Create new health bar for NPC
this.healthBar = new adsGame.HealthBar( this.pos.x , this.pos.y , this.health , this.npcData.tamanhoImagem.largura);
//test
// console.log("Testing this.healthBar.maxHealth:" , this.healthBar.maxHealth);
// Remove NPC time after die
this.removeTime = 5000;
// Keep this last direction to change only when npc change is direction
this.lastDirection = this.direction;
}
// New on melonjs 0.9.7
if ( this.npcData.atualizarSempre !== undefined && this.npcData.atualizarSempre)
this.alwaysUpdate = true;
},
removeHealth : function removeHealth(hitPoints) {
// console.log("Call method in NPC...", this.npcData.nome);
this.health = this.health - hitPoints;
},
setNPCHealth : function removeHealth( health ) {
this.health = health;
},
setDirection : function() {
// Get the distance between the two points to set the direction of NPC
this.distanceX = Math.abs(this.destX - this.pos.x);
this.distanceY = Math.abs(this.destY - this.pos.y);
if (this.distanceX > this.distanceY) {
this.direction = this.destX < this.pos.x ? 'left' : 'right';
} else {
this.direction = this.destY < this.pos.y ? 'up' : 'down';
}
},
updateThrower : function updateThrower( direction ) {
// thrower position depends on NPC direction
var addToPosX;
var addToPosY;
var heroAux = adsGame.heroEntity();
// angleToHero = this.angleTo(heroAux);
// console.log("this.angleTo hero:", angleToHero * 10);
// But this values on Json to work with any NPC that attack
// TODO - Make only when change direction to improve velocity
switch ( direction ) {
case "left":
addToPosX = this.npcData.posicaoAtirador.left[0];
addToPosY = this.npcData.posicaoAtirador.left[1];
break;
case "right":
addToPosX = this.npcData.posicaoAtirador.right[0];
addToPosY = this.npcData.posicaoAtirador.right[1];
break;
case "up":
addToPosX = this.npcData.posicaoAtirador.up[0];
addToPosY = this.npcData.posicaoAtirador.up[1];
break;
case "down":
addToPosX = this.npcData.posicaoAtirador.down[0];
addToPosY = this.npcData.posicaoAtirador.down[1];
break;
}
// Make only when change direction to improve velocity ( Removed this.lastDirection = this.direction; )
if ( this.thrower.throwerData.animacoes.animaTodasPosicoes ) {
// Change Z index when NPC UP
if ( this.direction !== "up" && this.direction !== "left"){
this.thrower.z = this.z + 1;
}else{
this.thrower.z = this.z - 1;
}
// if ( this.name === "toughbeard"){
// console.log ("this.direction:", this.direction);
// }
//
this.thrower.renderable.setCurrentAnimation( direction.toString() );
me.game.sort();
// Keep this last direction to change only when npc change is direction
this.lastDirection = this.direction;
}
this.thrower.pos.x = (this.pos.x + addToPosX);
this.thrower.pos.y = (this.pos.y + addToPosY);
},
//Update npc position.
update : function() {
// If NPC is death but is in the map don't update movement
if (!this.alive) {
return;
}
if (!this.alwaysUpdate && !this.stop){
this.alwaysUpdate = true;
// console.log("Always Updated...", this.npcData.nome);
}
// Update thrower position follow NPC
if (this.npcData.ataca) {
this.updateThrower( this.direction );
}
// Check collision
// ***************** IMPROVE COLLISION TO COLIDE AND GO BACK *********************
var res = me.game.collide(this);
if (res) {
if (res.obj.name == 'hero' && !this.eventHappening) {
// TODO - Change NPC direction to opposite side of the hero
// If json falaComHeroi == true then talk to hero if not skip this step
if (this.npcData.falaComHeroi){
// TODO - Play sound only one time lsee in hero entity
// play a "hmmquestionfemale" sound
if ( !this.helloSound ){
this.helloSound = true;
if ( this.npcData.nomeSom !== undefined && this.npcData.volumeEfeito !== undefined){
// play a "throwerSound" sound
me.audio.play( this.npcData.nomeSom , false , null , this.npcData.volumeEfeito );
}
}
//Show last message on messages data if this.msgData.msg null
if ( this.msgData.msg == undefined ){
this.msgData.msg = language.npcs[this.npcData.mensagem][language.npcs[this.npcData.mensagem].length - 1];
}
this.message.show(this.msgData);
}
this.message.messageShowing = true;
// msgShowing = true;
//Stop npc when he talk with hero
// Change NPC direction to opposite side of the hero if hero collide with NPC
// If NPC collide with hero don't change that otherwise they are on his back
var auxNPCDirection = this.direction;
if ( this.changeNPCDirection ){
// Get hero direction
var heroAux = adsGame.heroEntity();
// Opposite direction of hero
if ( heroAux.direction == "left" )
auxNPCDirection = "right";
else if (heroAux.direction == "right")
auxNPCDirection = "left";
else if ( heroAux.direction == "up" )
auxNPCDirection = "down";
else
auxNPCDirection = "up";
// If NPC have a weapon change this direction and position
if (this.npcData.ataca){
// Update thrower direction and position
this.updateThrower( auxNPCDirection );
}
// To test if is hero that collide with npc or the opposite
this.heroChangeDirection = false;
}
// New NPC animation stand opposite direction of the hero
if ( !this.firstAnimation ){
this.renderable.setCurrentAnimation("stand-" + auxNPCDirection);
}else{
this.renderable.setCurrentAnimation( "primeiraAnimacao" );
}
this.accel.x = this.accel.y = 0;
this.vel.x = this.vel.y = 0;
}
} else if (this.message.messageShowing && !this.talkEventHappening) {
// If json falaComHeroi == true then talk to hero if not skip this step
if (this.npcData.falaComHeroi){
this.helloSound = false;
this.message.hide();
}
// msgShowing = false;
this.message.messageShowing = false;
//Move npc when he stop talk with hero if is not stoped yet
if (!this.stop) {
this.accel.x = this.accel.y = this.npcData.velocidade;
if ( !this.firstAnimation ){
this.renderable.setCurrentAnimation(this.direction);
}else{
this.renderable.setCurrentAnimation( "primeiraAnimacao" );
}
// Reset to the next collision
this.changeNPCDirection = true;
// To test if is hero that collide with npc or the opposite
this.heroChangeDirection = true;
}
}
// If NPC collide with hero set collideHero = true otherwise set false to use on sellItems event
if ( res && res.obj.name == 'hero' ){
this.collideHero = true;
}else {
this.collideHero = false;
}
// *** IMPROVE THIS ONE - MAKE IT DINAMIC IF IS PRISONER OR NOT
if (this.npcData.categoria == "enemies" || this.npcData.categoria == "friends" || (this.npcData.categoria == "prisoner" && adsGame.prisonDoors.prisonDoorTrigger[this.npcData.prisao.numero])) {
//if return true then wait else no wait time then can readwaittime again
this.eventHappening = this.npcEvent(this.npcEvents);
// Check if there is a wait time
if (this.eventHappening) {
return;
} else {
this.readOneTimeEvent = false;
}
}
if ( this.prisoner ) {
if ( adsGame.prisonDoors.getPrisonDoorState( this.npcData.prisao.numero ) ) {
// Free NPC prisoner
if ( this.npcData.portaAbertaLiberta === undefined || this.npcData.portaAbertaLiberta) {
this.freeNPCPrisoner();
}
}
// console.log ('Prisoner ' , this.npcData.nome , ' is arrested at cell ' , this.npcData.prisao.numero ,
// ' and this cell is ' , prisonBreak[this.npcData.prisao.numero] ? 'open' : 'closed' );
}
//If NPC movement is path
if (this.npcData.tipoMovimento == "path") {
// Move NPC
if (moveObject(this) && !this.stop) {
if (this.countPath != this.path[this.currentPath].length) {
//return movement
this.accel.x = this.accel.y = this.npcData.velocidade;
// if ( !this.firstAnimation ){
// this.setCurrentAnimation(this.direction);
// }else{
// this.setCurrentAnimation( "primeiraAnimacao" );
// }
this.destX = this.path[this.currentPath][this.countPath ][0] * ads_tile_size;
this.destY = (this.path[this.currentPath][this.countPath ][1] * ads_tile_size) - this.avoidWall;
this.countPath++;
this.setDirection();
// first animation before set prisoner free
if ( !this.firstAnimation ){
this.renderable.setCurrentAnimation(this.direction);
}else{
this.renderable.setCurrentAnimation( "primeiraAnimacao" );
}
} else {
this.countPath = 0;
this.currentPath++;
// if that happen then NPC follow hero and now return to initial path
if ( this.currentPath == this.npcData.coordenadas.length + 2) {
this.currentPath = 0;
}
//Test if there is reverse path
if (this.reversePathNumber == this.currentPath) {
this.currentPath = 0;
}
// Stop the player
if (this.currentPath == this.path.length) {
this.stop = true;
// Set always update to false the npc is stoped
if (this.alwaysUpdate){
this.alwaysUpdate = false;
// console.log("Reached the end stop update...", this.npcData.nome);
}
// this.setCurrentAnimation("stand-" + this.direction);
if ( !this.firstAnimation ){
this.renderable.setCurrentAnimation( "stand-down");
}else{
this.renderable.setCurrentAnimation( "primeiraAnimacao" );
}
}
}
}
var player = adsGame.heroEntity();
if ( typeof (this.npcData.atacaDistancia ) !== "undefined" && this.npcData.atacaDistancia > this.distanceTo(player) ){
// console.log(" follow - Distance to attack: " , this.distanceTo(player));
this.countPath = 0;
this.npcData.tipoMovimento = "npcFollowHero";
}
} else if (this.npcData.tipoMovimento == "followhero") {
if ( !this.stop ){
this.velocityFollow = this.npcData.velocidade;
}
else{
this.velocityFollow = 0;
return;
}
followHero(this);
var player = adsGame.heroEntity();
var playerPosX = player.pos.x;
var playerPosY = player.pos.y;
this.distanceX = Math.abs(playerPosX - this.pos.x);
this.distanceY = Math.abs(playerPosY - this.pos.y);
// console.log("Distance x:" , this.distanceX, " Distance y:", this.distanceY);
// console.log("Distance x:" , this.distanceX, " Distance y:", this.distanceY);
if (this.distanceX > this.distanceY) {
this.direction = playerPosX < this.pos.x ? 'left' : 'right';
} else {
this.direction = playerPosY < this.pos.y ? 'up' : 'down';
}
// Stop the player
if (this.npcData.paraDistancia > this.distanceTo(player)) {
this.renderable.setCurrentAnimation("stand-" + this.direction);
this.accel.x = this.accel.y = 0;
this.vel.x = this.vel.y = 0;
} else {// if distance between player bigger than defined on json
// check and update movement - Update animation
this.renderable.setCurrentAnimation(this.direction);
this.accel.x = this.accel.y = this.npcData.velocidade;
}
} else if (this.npcData.tipoMovimento == "npcFollowHero") {
var player = adsGame.heroEntity();
if (this.countPath == 0){
var initStartX = Math.round( this.pos.x / ads_tile_size);
var initStartY = Math.round( ( this.pos.y ) / ads_tile_size);
var initDestX = Math.round( player.pos.x / ads_tile_size);
var initDestY = Math.round( ( player.pos.y + this.avoidWall ) / ads_tile_size);
var start = [initStartX, initStartY];
var end = [initDestX, initDestY];
this.heroFollowPath = adsGame.pathFinder.getPath(start, end);
this.destX = this.heroFollowPath[0][0] * ads_tile_size;
this.destY = this.heroFollowPath[0][1] * ads_tile_size - this.avoidWall;
}
// Move NPC
if (moveObject(this) && !this.stop) {
if (this.countPath != this.heroFollowPath.length) {
//return movement
this.accel.x = this.accel.y = this.npcData.velocidade;
this.renderable.setCurrentAnimation(this.direction);
this.destX = this.heroFollowPath[this.countPath ][0] * ads_tile_size;
this.destY = (this.heroFollowPath[this.countPath ][1] * ads_tile_size) - this.avoidWall;
this.countPath++;
this.setDirection();
this.renderable.setCurrentAnimation(this.direction);
} else {
this.countPath = 0;
// console.log("... Calculate new path follow hero---");
this.renderable.setCurrentAnimation("stand-" + this.direction);
// this.setCurrentAnimation( "stand-down" );
}
}
// - this.distanceTo(player) - this.npcData.tamanhoImagem.altura NPC height
if ( typeof (this.npcData.atacaDistancia ) !== "undefined" && this.npcData.atacaDistancia < ( this.distanceTo(player) - this.npcData.tamanhoImagem.altura ) ){
// console.log(" Not follow - Distance to attack: " , this.distanceTo(player));
this.countPath = 0;
this.currentPath = this.npcData.coordenadas.length + 1;
this.npcData.tipoMovimento = "path";
var startX = Math.round( this.pos.x / ads_tile_size);
var startY = Math.round( ( this.pos.y ) / ads_tile_size);
var destX = this.npcData.coordenadas[0].initStartX;
var destY = this.npcData.coordenadas[0].initStartY;
var start = [startX, startY];
var end = [ destX , destY ];
this.path[this.currentPath] = adsGame.pathFinder.getPath(start, end);
// console.log("pathlength:", this.path.length);
this.destX = this.path[this.currentPath][0][0] * ads_tile_size;
this.destY = (this.path[this.currentPath][0][1] * ads_tile_size) - this.avoidWall;
}
}
// check & update NPC movement
updated = this.updateMovement();
// update animation
if (updated)
{
// Actualizar animação
this.parent(this);
}
return updated;
}, // end update
// *** npcTalkEvent Managment
npcTalkEvent : function npcTalkEvent() {
// read event wait time
if (!this.readOneTimeEvent) {
this.waitEvent = this.currentEvent.tempo * 60;
this.readOneTimeEvent = true;
// Event talk is happening to prevent hide message
this.talkEventHappening = true;
//Show message
this.messageNumber = 0;
// Change to calculate the number of conversations on currentevent
// this.pauseMessage = Math.floor(this.waitEvent / this.npcData.mensagem.length);
this.pauseMessage = Math.floor(this.waitEvent / this.currentEvent.conversa.length);
//Add Dialogue animation
var playerPosX = adsGame.heroEntity().pos.x;
var playerPosY = adsGame.heroEntity().pos.y;
this.dialogueAnimation = new effect(
this.pos.x + 30 , this.pos.y - 10, // Coordinates
me.loader.getImage("dialoge"), // Image
18 , 19, // Size
[0,1,2,3], //Animation sheet
5, // Speed between 0 - Slowest and 60 - fastest
true, // Repeat animation
10 // Wait between animations 10 milliseconds
);
//Add Dialogue animation
this.exclamationAnimation = new effect(
playerPosX + 30 , playerPosY - 10, // Coordinates
me.loader.getImage("exclamation"), // Image
17 , 17, // Size
[0,1], //Animation sheet
5, // Speed between 0 - Slowest and 60 - fastest
true, // Repeat animation
10 // Wait between animations 10 milliseconds
);
me.game.add( this.exclamationAnimation, 6);
me.game.add( this.dialogueAnimation, 6);
me.game.sort();
console.log("How many times reading message show");
}
// console.log('this.currentEvent.conversa:' , this.currentEvent.conversa , 'this.messageNumber:' , this.messageNumber );
// this.msgData.msg = this.npcData.mensagem[0];
// $('.msgText,#hiddenText').html( this.msgData.msg );
// On event talk Show mouse left click image on message layer
$('.mouseLeftClick').show();
// Stop hero while message is showing
var player = adsGame.heroEntity();
player.setVelocity(0,0);
// Change dialogue depending on the number of messages divided by the waiting time
if ( ( ( this.waitEvent == ( (this.currentEvent.tempo * 60) - (this.pauseMessage * this.messageNumber + 1))) || this.message.leftClickMouse ) && this.messageNumber < this.currentEvent.conversa.length + 1 ) {
this.msgData.msg = language.npcs[this.npcData.mensagem][this.currentEvent.conversa[this.messageNumber]];
// Show new message
$('.msgText').html(this.msgData.msg);
// $('.msgText').fadeIn(1000);
this.messageNumber++;
this.message.show(this.msgData);
this.message.leftClickMouse = false;
}
// if ( this.npcData.nome == "Lief"){
// console.log ("this.message.leftClickMouse:" , this.message.leftClickMouse);
// console.log ("this.messageNumber:" , this.messageNumber);
// console.log ("this.currentEvent.conversa.length:" , this.currentEvent.conversa.length );
// }
// msgShowing = true;
if (--this.waitEvent < 0 || this.messageNumber > this.currentEvent.conversa.length ) {
// Hide message
this.message.hide();
// msgShowing = false;
this.message.messageShowing = false;
// New event
this.CurrentEventNumber++;
// Event is not happening anymore
this.talkEventHappening = false;
// Get hero velocity
var heroVelocity = me.game.HUD.getItemValue("velocidade") / 2;
// Player gets is velocity again
player.setVelocity( heroVelocity , heroVelocity );
// Destroy variable
player = undefined;
// Remove dialogue animation
me.game.remove( this.dialogueAnimation );
// Remove exclamation animation
me.game.remove( this.exclamationAnimation );
return false;
// Event end...~~
} else {
return true;
// Event happening
}
}, // end npcTalkEvent
// *** npcWaitEvent Managment
npcWaitEvent : function npcWaitEvent() {
if (!this.readOneTimeEvent) {
this.waitEvent = this.currentEvent.tempo * 60;
this.readOneTimeEvent = true;
}
if (--this.waitEvent < 0) {
this.CurrentEventNumber++;
// New event
return false;
} else {
return true;
// Event happening
}
}, // end npcWaitEvent
// *** npceffectEvent Managment
npceffectEvent : function npceffectEvent() {
if (!this.readOneTimeEvent) {
this.waitEvent = this.currentEvent.tempo * 60;
this.readOneTimeEvent = true;
// ***** ATTENTION CAN BE OTHER EFFECTS LIKE FIRE ...
// CHECK IF IS A DOOR REMOVE
//Remove door and play explosion effect
if (this.currentEvent.efeito == "explodeDoor") {
// Shake viewport on explosion
me.game.viewport.shake (20 , 600);
adsGame.prisonDoors.remove(this.currentEvent.coordenadasAlvo, this.currentEvent.efeito);
}
}
if (--this.waitEvent < 0) {
this.CurrentEventNumber++;
// New event
return false;
} else {
return true;
// Event happening
}
}, // end npceffectEvent
// *** Event Managment
npcEvent : function npcEvent(npcEvents) {
// console.log('this.CurrentEventNumber:' , this.CurrentEventNumber);
// If no more events return else execute the next event
if (this.CurrentEventNumber == npcEvents.length) {
return;
} else {
this.currentEvent = npcEvents[this.CurrentEventNumber];
}
switch( this.currentEvent.tipo ) {
case "talk":
//**** CHANGE THIS FOR COORDINATES INSTEAD PATH
// if( this.currentEvent.caminho == this.currentPath && this.currentEvent.passo == this.countPath){
// TODO - Review npc talk event how it's trigged
if ((this.currentEvent.coordenadas[0] == Math.round(this.pos.x / ads_tile_size) && this.currentEvent.coordenadas[1] == Math.round(this.pos.y / ads_tile_size)) || adsGame.prisonDoors.prisonDoorTrigger[this.npcData.prisao.numero]) {// to talk to prisoner if hero pull the trigger
if (this.npcTalkEvent()) {
// event talking is happening
npcTalking = true;
return true;
} else {
// event talking is over
npcTalking = false;
return false;
}
}
break;
case "wait":
// if( this.currentEvent.caminho == this.currentPath && this.currentEvent.passo == this.countPath){
if (this.currentEvent.coordenadas[0] == Math.round(this.pos.x / ads_tile_size) && this.currentEvent.coordenadas[1] == Math.round(this.pos.y / ads_tile_size)) {
if (this.npcWaitEvent()) {
return true;
} else {
return false;
}
}
break;
case "effect":
// if( this.currentEvent.caminho == this.currentPath && this.currentEvent.passo == this.countPath){
if (this.currentEvent.coordenadas[0] == Math.round(this.pos.x / ads_tile_size) && this.currentEvent.coordenadas[1] == Math.round(this.pos.y / ads_tile_size)) {
if (this.npceffectEvent()) {
return true;
} else {
return false;
}
}
break;
case "escape":
// this.readOneTimeEvent = false;
if (this.npcTalkEvent()) {
return true;
} else {
// Calculate new path
// console.log('Calculate path on trigger ...');
this.currentPath = this.path.length - 1;
this.countPath = 0;
var start = [Math.round(this.pos.x / ads_tile_size), Math.round(this.pos.y / ads_tile_size)];
var end = this.currentEvent.coordenadas;
this.path[this.currentPath] = adsGame.pathFinder.getPath(start, end, "collision");
// Stay on waiting room
this.reversePathNumber = -1;
return false;
}
break;
case "giveItem":
// this.readOneTimeEvent = false;
if (this.npcTalkEvent()) {
return true;
} else {
//Keep data for all items found by the hero less gold and knowledge increment right away
if (ads_items_data[this.currentEvent.item].categoria == 'ouro' ||
ads_items_data[this.currentEvent.item].categoria == 'conhecimento'){
me.game.HUD.updateItemValue(ads_items_data[this.currentEvent.item].categoria , parseInt(ads_items_data[this.currentEvent.item].valor, 10));
}else{
// Show inventory window if is not open
if (!adsGame.Inventory.isShowing) {
adsGame.Inventory.show();
// console.log('Inventory is not showing...');
}
// If npc give to hero a mission item then set as special item to go the rigth slot (Map items)
if (ads_items_data[this.currentEvent.item].categoria == 'itemMissao') {
ads_items_data[this.currentEvent.item].specialItem = true;
}
// Add item to hero
adsGame.Inventory.addItem(ads_items_data[this.currentEvent.item]);
return false;
}
}
break;
case "sellItems":
if( this.collideHero ){
adsGame.shop.show( this.npcData );
}else{
// console.log("Don't sell item to hero:");
if ( showingShop ){
adsGame.shop.hide();
}
}
break; // Sell talk
default:
break;
}
},
"freeNPCPrisoner" : function freeNPCPrisoner(context) {
// console.log ('Says thx to hero and.. ');
// console.log ('Calculate path to freedom... :)');
// console.log ('Stop being a prisoner...');
// If open prisoner cell door releases the prisoner
//Stop being a prisoner...