-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEngine.js
More file actions
2895 lines (2245 loc) · 85.7 KB
/
Engine.js
File metadata and controls
2895 lines (2245 loc) · 85.7 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
/** @type {HTMLCanvasElement} */
export class Utilities{
static variableCopy(obj){
return Object.assign(Object.create(Object.getPrototypeOf(obj)), obj);
}
static controlUseVector2DType(vector2D){
if(vector2D && vector2D.NAME() && vector2D.NAME() === "Vector2D"){
return true;
}else{
throw new Error("I don't know instantiated with a Vector2D or passed as an argument a required Vector2D");
}
}
static controlUseNumberType(arrayNumberVerify){
if( !Array.isArray(arrayNumberVerify) ){
if(isNaN(arrayNumberVerify)){
throw new Error("Argument required of Number type ");
}
}else{
arrayNumberVerify.forEach(element => {
if(isNaN(element)){
throw new Error("Argument required of Number type ");
}
});
}
return true;
}
static controlUseCollider2DType(collider2D){
if(collider2D && collider2D.NAME && collider2D.NAME() === "PoligonCollider2D" ||
collider2D.NAME() === "RectangleCollider2D" ||
collider2D.NAME() === "CircleCollider2D" ||
collider2D.NAME() === "AABBCollider2D")
{
return true;
}else{
throw new Error("The collider instance must be one of the types of the Collider2D class:"+
"PoligonCollider2D or RectangleCollider2D or CircleCollider2D or AABBCollider2D");
}
}
static controlUseCollisionFilterType(collisionFilter){
if(collisionFilter && collisionFilter.NAME && collisionFilter.NAME() == "CollisionFilter"){
return true;
}else{
throw new Error("Argument required of CollisionFilter type ");
}
}
static controlUseImageType(image){
if(image instanceof Image && image.complete){
return true;
}else{
throw new Error("Argument required of Image type and complete loaded");
}
}
static controlUseAudioType(audio){
if(audio instanceof Audio && image.readyState === 4){
return true;
}else{
throw new Error("Argument required of Audio type and complete loaded");
}
}
static controlUseAnimationSpriteType(animationSprite){
if(animationSprite && animationSprite.NAME && animationSprite.NAME() == "AnimationSprite"){
return true;
}else{
throw new Error("Argument required of AnimationSprite type");
}
}
static controlUseStringType(valor){
if(typeof valor === 'string'){
return true;
}else{
throw new Error("Argument required of string type");
}
}
static controlUseSpriteType(sprite){
if(sprite && sprite.NAME && sprite.NAME() == "Sprite"){
return true;
}else{
throw new Error("Argument required of Sprite type");
}
}
static controlUseBooleanType(valor){
if(typeof valor === 'boolean'){
return true;
}else{
throw new Error("Argument required of boolean type");
}
}
static controlUseTranformType(tranform){
if(tranform && tranform.NAME && tranform.NAME() == "Tranform"){
return true;
}else{
throw new Error("Argument required of Tranform type");
}
}
static controlUseRigidBodyType(rigidBody2D){
if(rigidBody2D && rigidBody2D.NAME && rigidBody2D.NAME() == "RigidBody2D"){
return true;
}else{
throw new Error("Argument required of RigidBody2D type");
}
}
static controlUseComponentType(component){
if(component && component.NAME && component.NAME() == "Component"){
return true;
}else{
throw new Error("Argument required of Component type");
}
}
static controlUseCompositeType(Composite){
if(Composite && Composite.NAME && Composite.NAME() == "Composite"){
return true;
}else{
throw new Error("Argument required of Composite type");
}
}
static controlUseSceneType(scene){
if(scene && scene.NAME && scene.NAME() == "Scene"){
return true;
}else{
throw new Error("Argument required of Scene type");
}
}
}
export class Vector2D {
x;
y;
_NAME = "Vector2D";
constructor(x = 0, y = 0){
if(!isNaN(x) && !isNaN(y)){
this.x = x;
this.y = y;
}else {
throw new Error("The components (x,y) of the vector must be real numbers or integers");
}
}
NAME(){
return this._NAME;
}
rotate(angle){
let cos = Math.cos(angle);
let sin = Math.sin(angle);
let x = this.x * cos - this.y * sin;
let y = this.x * sin + this.y * cos;
return new Vector2D(x, y);
}
rotateAbout = function(angle, point) {
//Rotar alrededor del punto
let cos = Math.cos(angle);
let sin = Math.sin(angle);
let x = point.x + ((this.x - point.x) * cos - (this.y - point.y) * sin);
let y = point.y + ((this.x - point.x) * sin + (this.y - point.y) * cos);
return new Vector2D(x, y);
};
static angle(vectorA, vectorB){
//X: Mouse.position.X - player.position.X + player.ancho/2 --> tener en cuenta en el vector de parametro
let distancia = Vector2D.vectorDistance(vectorA, vectorB);
return Math.atan2(distancia.x, distancia.y);
}
static catetos(VectorA, vectorB){
//Define la direccion x,y,z del movimiento de un origen a un punto destino al sumar a la posicion
let angulo = Vector2D.angle(VectorA, vectorB);
return new Vector2D(Math.sin(angulo), Math.cos(angulo));
}
static vectorDistance(vectorA, vectorB){ //direccion
// X += radio1 - radio2 --> esto considerar al crear el vector
// Y += radio1 - radio2
return new Vector2D(vectorA.x - vectorB.x, vectorA.y - vectorB.y);
}
static distance(vectorA , vectorB){// Hipotenusa
let distance = Vector2D.vectorDistance(vectorA, vectorB);
return new Vector2D(distance.x * distance.x, distance.y * distance.y);
}
static productDot(vectorA, vectorB){
// = 0 => ortogonales entre si => 96 grados etre si
// != 0 => paralelos entre si
return vectorA.x * vectorB.x + vectorA.y * vectorB.y;
}
static productCross(vectorA,vectorB) {
return (vectorA.x * vectorB.y) - (vectorA.y * vectorB.x);
};
static productCross3(vectorA, vectorB, vectorC) {
return (vectorB.x - vectorA.x) * (vectorC.y - vectorA.y) - (vectorB.y - vectorA.y) * (vectorC.x - vectorA.x);
};
module(){ // Hipotenusa
return Math.sqrt(this.x * this.x, this.y * this.y);
}
static sum( vectorA, vectorB){
return new Vector2D(vectorA.x + vectorB.x, vectorA.y + vectorB.y);
}
static res( vectorA, vectorB){
return new Vector2D(vectorA.x - vectorB.x, vectorA.y - vectorB.y);
}
static mult(vector, scalar) {
return new Vector2D(vector.x * scalar, vector.y * scalar);
};
static div(vector, scalar) {
return new Vector2D(vector.x / scalar, vector.y / scalar);
};
//negacion
neg() {
return new Vector2D(-this.x, -this.y);;
};
//Retorna un vector perpendicular. Set `negate` to true for the perpendicular in the opposite direction.
perp(vector, negate) {
negate = negate === true ? -1 : 1;
return new Vector2D(negate * -vector.y, negate * vector.x);
};
}
export class Vertices2D{
_points = [];// lista de objetos {x: number, y: number}
_centre = null; //centro relativo a los vertices --> usado para posicionar los vertices a otro centro no relativo
#NAME = "Vertices2D";
constructor(arrayPoints){
this.setVertices(arrayPoints);
}
pointsRef(){
return this._points;
}
pointsCopy(){
return Utilities.variableCopy(this._points);
}
centreRef(){
return this._centre;
}
centerCopy(){
return Utilities.variableCopy(this._centre);
}
NAME(){
return this.#NAME;
}
setVertices(arrayPoints){
//Exsiste un vertice si exsiste una interseccion entre los extremos de dos segmentos
if(arrayPoints && arrayPoints.length > 2){
this._points = []
arrayPoints.forEach(point => this._points.push(new Vector2D(point.x, point.y)))
//this.#points = arrayPoints;
this._centre = this.calculateCentre();
}else{
throw new Error("The number of points must be greater than or equal to 3 for the existence of vertices (intersection of two segments) ");
}
}
/*
Vertices.inertia = function(vertices, mass) {
var numerator = 0,
denominator = 0,
v = vertices,
cross,
j;
// find the polygon's moment of inertia, using second moment of area
// from equations at http://www.physicsforums.com/showthread.php?t=25293
for (var n = 0; n < v.length; n++) {
j = (n + 1) % v.length;
cross = Math.abs(Vector.cross(v[j], v[n]));
numerator += cross * (Vector.dot(v[j], v[j]) + Vector.dot(v[j], v[n]) + Vector.dot(v[n], v[n]));
denominator += cross;
}
return (mass / 6) * (numerator / denominator);
};
*/
calculateCentre() {
let area = this.area(true);
let centre = { x: 0, y: 0 };
let j;
for (var i = 0; i < this._points.length; i++) {
j = (i + 1) % this._points.length;
let cross = Vector2D.productCross(this._points[i], this._points[j]);
let temp = Vector2D.mult(Vector2D.sum(this._points[i], this._points[j]), cross);
centre = Vector2D.sum(centre, temp);
}
return Vector2D.div(centre, 6 * area);
};
rotate(center, angle) {
const radians = angle * Math.PI / 180; // Convertir el ángulo a radianes
const cx = center.x; // Coordenada x del centro
const cy = center.y; // Coordenada y del centro
// Iterar sobre cada vértice
this._points = this._points.map(vertex => {
const { x, y } = vertex;
// Calcular las coordenadas relativas al centro
const rx = x - cx;
const ry = y - cy;
// Aplicar la rotación a las coordenadas relativas
const cosTheta = Math.cos(radians);
const sinTheta = Math.sin(radians);
const rotatedX = rx * cosTheta - ry * sinTheta;
const rotatedY = ry * cosTheta + rx * sinTheta;
// Sumar las coordenadas del centro a las coordenadas rotadas para obtener las coordenadas absolutas
const absoluteX = rotatedX + cx;
const absoluteY = rotatedY + cy;
return { x: absoluteX, y: absoluteY };
});
}
scale(scaleX, scaleY, point) {
if (scaleX === 1 && scaleY === 1)
return this._points;
point = point || this.calculateCentre();
for (var i = 0; i < this._points.length; i++) {
let vertex = this._points[i];
let delta = Vector2D.res(vertex, point);
this._points[i].x = point.x + delta.x * scaleX;
this._points[i].y = point.y + delta.y * scaleY;
}
};
traslate(vector2D){
if(Utilities.controlUseVector2DType(vector2D)){
for (let i = 0; i < this._points.length; i++) {
this._points[i].x += vector2D.x;
this._points[i].y += vector2D.y;
}
}
}
isConvex() {
// http://paulbourke.net/geometry/polygonmesh/
// Copyright (c) Paul Bourke (use permitted)
var flag = 0,
n = this._points.length,
i,
j,
k,
z;
if (n < 3)
return null;
for (i = 0; i < n; i++) {
j = (i + 1) % n;
k = (i + 2) % n;
z = (this._points[j].x - this._points[i].x) * (this._points[k].y - this._points[j].y);
z -= (this._points[j].y - this._points[i].y) * (this._points[k].x - this._points[j].x);
if (z < 0) {
flag |= 1;
} else if (z > 0) {
flag |= 2;
}
if (flag === 3) {
return false;
}
}
if (flag !== 0){
return true;
} else {
return null;
}
};
area (signed) {
let area = 0;
let j = this._points.length - 1;
for (var i = 0; i < this._points.length; i++) {
area += (this._points[j].x - this._points[i].x) * (this._points[j].y + this._points[i].y);
j = i;
}
if (signed)
return area / 2;
return Math.abs(area) / 2;
};
}
class Collider2D {
_centre; //variacionLocalPosicion --> respecto a la posicion de dibujado
#NAME = "Collider2D";
density;
friction;
sensor;
constructor(centre){
if(Utilities.controlUseVector2DType(centre)){
this._centre = centre;
}/*else{
throw new Error("The collider2D has not been instantiated with its Vector2D center position");
}*/
}
centerCopy(){
return Utilities.variableCopy(this._centre);
}
NAME(){
return this.#NAME;
}
moveCenter(vector2D){
if(Utilities.controlUseVector2DType(vector2D)){
this._centre = vector2D;
}
}
//masa : number
//area : number
setDensity(masa, area){
//es la cantidad de masa contenido por unidad de area(2D) o volumen(3D).
//Una alta densidad indica que las partículas están más cercanas entre sí (mas compacto) => mayor peso y resistencia
//Una baja densidad => menor peso y menor resistncia(rigidez)
return masa/area;
}
setFiction(fractionForce){
//fuerza que se opone al movimiento
this.friction = fractionForce;
}
setSensor(boolean){
this.sensor = boolean
}
}
export class CircleCollider2D extends Collider2D{
#radius = 0;
#NAME = "CircleCollider2D";
constructor(centre = new Vector2D(0,0) , radius = 0){
super(centre);
if(radius && !isNaN(radius) && radius > 0){
this.#radius = radius;
}else{
throw new Error(" The radius of a CircleCollider2D must be a number greater than 0 ");
}
}
radius(){
return this.#radius;
}
scale(number){
this.#radius *= number;
}
traslate(vector2D){
if(Utilities.controlUseVector2DType(vector2D)){
this.moveCenter(new Vector2D(this.centerCopy().x + vector2D.x, this.centerCopy().y + vector2D.y));
}
}
NAME(){
return this.#NAME;
}
bounds(){
// Calcular los vértices del cuadro delimitador del círculo
let topLeft = new Vector2D(this.centerCopy().x - this.#radius, this.centerCopy().y - this.#radius);
let bottomRight = new Vector2D(this.centerCopy().x + this.#radius, this.centerCopy().y + this.#radius);
return {min_x: topLeft.x, max_x: bottomRight.x, min_y: topLeft.y, max_y: bottomRight.y}
}
}
export class PoligonCollider2D extends Collider2D{
_vertices;
_radio;
_bound;
#NAME = "PoligonCollider2D";
// centre == centro del sprite u objeto
constructor(centre = new Vector2D(0,0), vertices){
super(centre);
if(vertices && vertices.NAME && vertices.NAME() == "Vertices2D"){
this.realPositioningToCenterRef(centre, vertices)
this._vertices = vertices;
this._bound = this.AABB(vertices.pointsCopy());
}else if(vertices){
this._vertices = new Vertices2D(vertices);
this.realPositioningToCenterRef(centre, this._vertices)
this._bound = this.AABB(vertices);
}
}
realPositioningToCenterRef(centre, vertices){
let distance = Vector2D.res(centre, vertices.centreRef());
vertices.traslate(distance);
}
center(){
return this._vertices.calculateCentre();
}
createVerticesPoligon(centre, numSegmentos, radio) {
this._radio = radio
const vertices = []; // numSegmentos definir ese tamaño para no crear varios arreglos consumo de recursoso al ajutarse al tamaño
const angulo = (2 * Math.PI) / numSegmentos;
for (let i = 0; i < numSegmentos; i++) {
const x = centre.x + radio * Math.cos(angulo * i); // + this.position.x
const y = centre.y + radio * Math.sin(angulo * i);// + this.position.y
vertices.push({ x, y });
}
this._vertices = new Vertices2D(vertices);
this._bound = this.AABB(vertices); // Actualizar bounds
return vertices;
}
AABB(vertices){
let min_x = Infinity;
let max_x = -Infinity;
let min_y = Infinity;
let max_y = -Infinity;
for(let i=0; i < vertices.length; i++){
let x = vertices[i].x;
let y = vertices[i].y;
if(x < min_x )
min_x = x;
if(y < min_y)
min_y = y;
if(x > max_x )
max_x = x;
if(y > max_y)
max_y = y;
}
return {min_x, min_y, max_x, max_y};
}
boundsCopy(){
return Utilities.variableCopy({max_x:0, max_y:0, min_x:0, min_y:0},this._bound);
}
bounds(){
return this._bound;
}
verticesRef(){
return this._vertices.pointsRef();
}
verticesCopy(){
return this._vertices.pointsCopy();
}
//Al ser un atributo primitivo esta es obtenido por valor no por ref.
radio(){
return this._radio
}
area(signed){
return this._vertices.area(signed);;
}
scale(xScale, yScale, point){
this._vertices.scale(xScale, yScale, point);
this._bound = this.AABB(this._vertices.pointsRef());
}
rotate(angle, center){
this._vertices.rotate(center, angle);
this._bound = this.AABB(this._vertices.pointsRef()); // Actualizar bounds después de rotar
}
traslate(vector2D){
this._vertices.traslate(vector2D);
this._bound = this.AABB(this._vertices.pointsRef());
this.moveCenter(new Vector2D(this.centerCopy().x + vector2D.x, this.centerCopy().y + vector2D.y));
}
NAME(){
return this.#NAME
}
}
export class RectangleCollider2D extends PoligonCollider2D{
//centre : Vector2D
constructor(position = new Vector2D(0,0) , width = 4, height = 4){
let points = [
{x: position.x, y: position.y},
{x: position.x + width, y:position.y},
{x:position.x + width, y:position.y + height},
{x:position.x, y:position.y + height}
]
super(new Vector2D(position.x + width/2, position.y + height/2), points);
}
}
export class AABBCollider2D extends RectangleCollider2D{
//Este collider no puede ser rotado
#NAME = "AABBCollider2D"
constructor(position = new Vector2D(0,0), width = 4, height = 4){
super(position, width, height);
}
NAME(){
return this.#NAME
}
rotate(){}
}
export class Segment2D{
point1;
point2;
#NAME = "Segment2D";
constructor(vector2D1 = new Vector2D(0,0), vector2D2 = new Vector2D(0,10)){
if(vector2D1.NAME && vector2D2.NAME && vector2D2.NAME() === "Vector2D" && vector2D1.NAME() === "Vector2D"){
this.point1 = vector2D1;
this.point2 = vector2D2;
}else{
throw new Error("The AABBCollider2D has not been instantiated with its Vector2D");
}
}
NAME(){
return this.#NAME
}
}
export class CollisionFilter {
//Para el uso de camara => todo los componentes deben tener un rigidbody con AABB, de lo contrario no se pintara.
// Camara group 999 y category = 1 reservado para la camara y todo los componentes por defecto tendran la masck = 1 para colisionar con la camara y determinar si se encuentra dentro
// Si el valor es mayor a 0 e igual para dos componentes diferentes => colisionan
#group;
// Si el grupo es igual a cero o son diferentes entre los componentes => aplica categoria(especifica su id de colision)
#category; // (-5 camara)
// Este contendra todas las categorias con las que colisionara si no se aplica grupo
#mask;
static #TYPES = {"COMPONENT": 1, "COMPOSITE": 2}
#type;
#NAME = "CollisionFilter";
constructor(group = 0, category = 2, mask = [1, 2], type = CollisionFilter.TYPES().COMPONENT){
if(type == 1 || type == 2){
this.#type = type;
}else{
throw new Error("The type must be an enumerable of the TYPES() variable of this same class")
}
if(Utilities.controlUseNumberType([group, category]) && Array.isArray(mask)){
if(!mask.includes(1)){
mask.push(1);
}
this.#category = category;
this.#group = group;
this.#mask = mask;
}
}
static TYPES(){
return CollisionFilter.#TYPES;
}
setGroup(group = 0){
this.#group = group;
}
setCategory(category = 1){
this.#category = category;
}
setMask(mask = [1]){
this.#mask = mask;
}
group(){
return this.#group;
}
category(){
return this.#category;
}
mask(){
return this.#mask
}
NAME(){
return this.#NAME;
}
}
export class RigidBody2D{
_collisionFilter;
_collider2D;
#NAME = "RigidBody2D"
//------------ Para motor de fisica -------------
#type; //static : la fisica no lo afecta dianmic : la fisica lo afecta
#mass;
#gravityScale;
#angleVelocity;
#linearVelocity;
#linearDamping;
#angularDamping;
#fixedRotation; //rotacion fija
//------------ --------- ------- ------------
constructor(collider2D, collisionFilter){
this.setCollider2D(collider2D);
this.setColisionFilter(collisionFilter);
//TODO: instanciacion de atributos utilizados para motor de fisica
}
collider2D(){
return this._collider2D;
}
setCollider2D(collider2D){
if(Utilities.controlUseCollider2DType(collider2D)){
this._collider2D = collider2D;
}
}
colisionFilter(){
return this._collisionFilter;
}
setColisionFilter(collisionFilter){
if(Utilities.controlUseCollisionFilterType(collisionFilter)){
this._collisionFilter = collisionFilter;
}
}
NAME(){
return this.#NAME;
}
//TODO: pendiente para motor de fisica
applyForce(){}
applyAngularForce(){}
body(){
//objeto usado por matter.js
}
}
export class Tranform {
_position; // Posicion en la scena
_scale; // escala a aumentar de sprite y rigidbody
_angle; // angulo a tener sprite y rigidbody
_speed = 1;
_destinyMoveRef;
#NAME = "Tranform";
constructor(position = new Vector2D(0,0), scale = new Vector2D(1,1), angle = 0) {
this.setPosition(position);
this.setScale(scale);
this.setAngle(angle);
this._destinyMoveRef = this._position;
}
position(){
return Utilities.variableCopy(this._position);
}
setPosition(position){
if(Utilities.controlUseVector2DType(position)){
this._position = position;
}
}
scale(){
return this._scale;
}
setScale(scale){
if(Utilities.controlUseVector2DType(scale)){
this._scale = scale;
}
}
angle(){
return this._angle;
}
setAngle(angle){
if(Utilities.controlUseNumberType(angle)){
this._angle = angle;
}
}
//---------- Patron:Strategy (TIPOS DESPLAZAMIENTOS A UN DESTINO) --------------
directionDisplacementToDestiny(origen, destino){
/*
//Distancia en X e Y entre el jugador y este enemigo (pitagoras => ditancia total (hipotenuza) ente dos objetos)
this.distance = {
// x : (this.x + this.sprite.ancho/2 == radio) y:(this.y + this.sprite.alto/2 == radio) --> posicion del punto centro del objeto
x: ((this.position.X + this.scale.X/2) + this.radio) - ( (this.destinoMove.position.X + this.destinoMove.scale.X/2) + this.destinoMove.radio),
y: ((this.position.Y + this.scale.Y/2) + this.radio) - ( (this.destinoMove.position.Y + this.destinoMove.scale.Y/2) + this.destinoMove.radio),
}
const angle = Math.atan2(this.distance.x, this.distance.y); // Pitagoras
return {
X:this.velocity.X * Math.sin(angle),
Y:this.velocity.Y * Math.cos(angle)
};
*/
//let vectorOrigen = new Vector(this.centro.X + this.radio, this.centro.Y + this.radio, 0);
return Vector2D.catetos(origen,destino);
}
linearMoveToDestiny(dt, t){
/*
//let destino = new Vector(this.tranformDestinoMove.centro.X + this.tranformDestinoMove.radio,this.tranformDestinoMove.centro.Y + this.tranformDestinoMove.radio, 0);
let speed = this.getVelocidadEnDireccionDestino(this.vectorDestinoMoveRef);
this.position.X = this.position.X - speed.X ;
this.position.Y = this.position.Y - speed.Y ;
*/
let directionToDestiny = this.directionDisplacementToDestiny(this._position ,this._destinyMoveRef);
let desplacement = new Vector2D(0,0);
desplacement.x = this._position.x + directionToDestiny.x * this._speed;
desplacement.y = this._position.y + directionToDestiny.y * this._speed;
return desplacement;
}
circularMoveToDestiny(radio, angle, dt, t){
//-----------------------------------------------
//let destino = new Vector(this.tranformDestinoMove.centro.X + this.tranformDestinoMove.radio,this.tranformDestinoMove.centro.Y + this.tranformDestinoMove.radio, 0);
//->let speed = this.getVelocidadEnDireccionDestino(this.vectorDestinoMoveRef);
// if (this.frameGame % 10 === 0)//velocidad de movimiento circular
//Parametrica de la circunferencia:
//->let moveCircularX = this.radioMovimientoCircular * Math.cos(this.anguloRotacionRadian * t)*dt; // x = x + radio * cos(angleRadian*t)
//->let moveCirculary = this.radioMovimientoCircular * Math.sin(this.anguloRotacionRadian * t)*dt; //y = y + radio * sen(angleRadian*t)
//"PITAGORAS"
//--> Suma la speed '+' => gana distancia(huye). '-' => pierde distancia(persige) hasta tomar posicion del player {this.x - this.speed.x *50*dt}
//->this.position.X = (this.position.X - speed.X) + moveCircularX; // sin el moveCircularX => movimiento rectilineo uniforme en x
//->this.position.Y = (this.position.Y - speed.Y) + moveCirculary; // sin el moveCircularY => movimiento rectilineo uniforme en Y
// TODO: Al alcanzar la posicion del player => rota alrededor del mismo con los moveCircularX,moveCircularY.
//console.log("Angulo: ",this.anlgeRotation);
//console.log("Distancia: ",Math.sqrt(this.distance.x * this.distance.x + this.distance.y * this.distance.y));
//---------------------------------------------------------------------------------------------
let directionToDestiny = this.directionDisplacementToDestiny(this._position ,this._destinyMoveRef);
let moveCircularX = radio * Math.cos(angle * t)* dt; // x = x + radio * cos(angleRadian*t)
let moveCirculary = radio * Math.sin(angle * t)* dt; //y = y + radio * sen(angleRadian*t)
let desplacement = new Vector2D(0,0);
desplacement.x = (this._position.x - directionToDestiny.x * this._speed) + moveCircularX;
desplacement.y = (this._position.y - directionToDestiny.y * this._speed) + moveCirculary;
return desplacement;
}
setDestinoMove(vectorDestino){
if(Utilities.controlUseVector2DType(vectorDestino)){
this._destinyMoveRef = vectorDestino;
}
}
setSpeed(speed){
if(Utilities.controlUseNumberType(speed)){
this._speed = speed;
}
}
speed(){
return this._speed;
}
NAME(){
return this.#NAME;