-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
1949 lines (1663 loc) · 64.8 KB
/
index.js
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
/* eslint indent: ["error", 2, { "SwitchCase": 1 }] */
module.exports = module.exports.default = class TileUtilities {
constructor(renderingEngine = global.PIXI) {
if (renderingEngine === undefined) {
throw new Error(
'Please assign a rendering engine in the constructor before using bump.js'
)
}
// If the `renderingEngine` is Pixi, set up Pixi object aliases
if (renderingEngine.Container && renderingEngine.Sprite) {
this.renderingEngine = renderingEngine
this.Container = this.renderingEngine.Container
// backwards compatibility
if (
!this.renderingEngine.utils ||
!this.renderingEngine.utils.TextureCache
) {
try {
Object.defineProperty(this.renderingEngine, 'utils', {
value: { TextureCache: {} }
})
} catch (err) {
console.warn(err.message || err)
}
}
this.TextureCache = this.renderingEngine.utils.TextureCache
this.Texture = this.renderingEngine.Texture
this.Sprite = this.renderingEngine.Sprite
this.Rectangle = this.renderingEngine.Rectangle
this.Graphics = this.renderingEngine.Graphics
this.Assets = this.renderingEngine.Assets || {}
this.loader = this.Assets.loader || {}
this.resources = this.loader.resources || {}
}
}
// Make a texture from a frame in another texture or image
frame(textureOrPath, x, y, width, height) {
if (!textureOrPath) {
return this.Texture.EMPTY
}
const { source } =
typeof textureOrPath === 'string'
? this.Texture.from(textureOrPath)
: textureOrPath
return new this.Texture({
source,
frame: new this.Rectangle(x, y, width, height)
})
}
// #### getIndex
// The `getIndex` helper method
// converts a sprite's x and y position to an array index number.
// It returns a single index value that tells you the map array
// index number that the sprite is in
getIndex(x, y, tilewidth, tileheight, mapWidthInTiles) {
const index = {}
// Convert pixel coordinates to map index coordinates
index.x = Math.floor(x / tilewidth)
index.y = Math.floor(y / tileheight)
// Return the index number
return index.x + index.y * mapWidthInTiles
}
/*
#### getTile
The `getTile` helper method
converts a tile's index number into x/y screen
coordinates, and capture's the tile's grid index (`gid`) number.
It returns an object with `x`, `y`, `centerX`, `centerY`, `width`, `height`, `halfWidth`
`halffHeight` and `gid` properties. (The `gid` number is the value that the tile has in the
mapArray) This lets you use the returned object
with the 2d geometric collision functions like `hitTestRectangle`
or `rectangleCollision`
The `world` object requires these properties:
`x`, `y`, `tilewidth`, `tileheight` and `widthInTiles`
*/
getTile(index, mapArray, world) {
const tile = {}
tile.gid = mapArray[index]
tile.width = world.tilewidth
tile.height = world.tileheight
tile.halfWidth = world.tilewidth / 2
tile.halfHeight = world.tileheight / 2
tile.x = (index % world.widthInTiles) * world.tilewidth + world.x
tile.y = Math.floor(index / world.widthInTiles) * world.tileheight + world.y
tile.gx = tile.x
tile.gy = tile.y
tile.centerX = tile.x + world.tilewidth / 2
tile.centery = tile.y + world.tileheight / 2
// Return the tile object
return tile
}
/*
#### surroundingCells
The `surroundingCells` helper method returns an array containing 9
index numbers of map array cells around any given index number.
Use it for an efficient broadphase/narrowphase collision test.
The 2 arguments are the index number that represents the center cell,
and the width of the map array.
*/
surroundingCells(index, widthInTiles) {
return [
index - widthInTiles - 1,
index - widthInTiles,
index - widthInTiles + 1,
index - 1,
index,
index + 1,
index + widthInTiles - 1,
index + widthInTiles,
index + widthInTiles + 1
]
}
// #### getPoints
/*
The `getPoints` method takes a sprite and returns
an object that tells you what all its corner points are. The return
object has four properties, each of which is an object with `x` and `y` properties:
- `topLeft`: `x` and `y` properties describing the top left corner
point.
- `topRight`: `x` and `y` properties describing the top right corner
point.
- `bottomLeft`: `x` and `y` properties describing the bottom left corner
point.
- `bottomRight`: `x` and `y` properties describing the bottom right corner
point.
If the sprite has a `collisionArea` property that defines a
smaller rectangular area inside the sprite, that collision
area can be used instead for collisions instead of the sprite's dimensions. Here's
How you could define a `collsionArea` on a sprite called `elf`:
```js
elf.collisionArea = {x: 22, y: 44, width: 20, height: 20};
```
Here's how you could use the `getPoints` method to find all the collision area's corner points.
```js
let cornerPoints = tu.getPoints(elf.collisionArea);
```
*/
getPoints(s) {
const ca = s.collisionArea
if (ca !== undefined) {
return {
topLeft: {
x: s.x + ca.x,
y: s.y + ca.y
},
topRight: {
x: s.x + ca.x + ca.width,
y: s.y + ca.y
},
bottomLeft: {
x: s.x + ca.x,
y: s.y + ca.y + ca.height
},
bottomRight: {
x: s.x + ca.x + ca.width,
y: s.y + ca.y + ca.height
}
}
}
return {
topLeft: {
x: s.x,
y: s.y
},
topRight: {
x: s.x + s.width - 1,
y: s.y
},
bottomLeft: {
x: s.x,
y: s.y + s.height - 1
},
bottomRight: {
x: s.x + s.width - 1,
y: s.y + s.height - 1
}
}
}
// ### hitTestTile
/*
`hitTestTile` checks for a
collision between a sprite and a tile in any map array that you
specify. It returns a `collision` object.
`collision.hit` is a Boolean that tells you if a sprite is colliding
with the tile that you're checking. `collision.index` tells you the
map array's index number of the colliding sprite. You can check for
a collision with the tile against "every" corner point on the
sprite, "some" corner points, or the sprite's "center" point.
`hitTestTile` arguments:
sprite, array, collisionTileGridIdNumber, worldObject, spritesPointsToCheck
```js
tu.hitTestTile(sprite, array, collisioGid, world, pointsToCheck);
```
The `world` object (the 4th argument) has to have these properties:
`tileheight`, `tilewidth`, `widthInTiles`.
Here's how you could use `hitTestTile` to check for a collision between a sprite
called `alien` and an array of wall sprites with map gid numbers of 0.
```js
let alienVsFloor = g.hitTestTile(alien, wallMapArray, 0, world, "every");
```
*/
hitTestTile(sprite, mapArray, gidToCheck, world, pointsToCheck) {
// The `checkPoints` helper function Loop through the sprite's corner points to
// find out if they are inside an array cell that you're interested in.
// Return `true` if they are
const checkPoints = (key) => {
// Get a reference to the current point to check.
// (`topLeft`, `topRight`, `bottomLeft` or `bottomRight` )
const point = sprite.collisionPoints[key]
// Find the point's index number in the map array
collision.index = this.getIndex(
point.x,
point.y,
world.tilewidth,
world.tileheight,
world.widthInTiles
)
// Find out what the gid value is in the map position
// that the point is currently over
collision.gid = mapArray[collision.index]
// If it matches the value of the gid that we're interested, in
// then there's been a collision
if (collision.gid === gidToCheck) {
return true
}
return false
}
// Assign "some" as the default value for `pointsToCheck`
pointsToCheck = pointsToCheck || 'some'
// The collision object that will be returned by this function
const collision = {}
// Which points do you want to check?
// "every", "some" or "center"?
switch (pointsToCheck) {
case 'center':
// `hit` will be true only if the center point is touching
sprite.collisionPoints = {
center: {
x: sprite.centerX,
y: sprite.centerY
}
}
collision.hit = Object.keys(sprite.collisionPoints).some(checkPoints)
break
case 'every':
// `hit` will be true if every point is touching
sprite.collisionPoints = this.getPoints(sprite)
collision.hit = Object.keys(sprite.collisionPoints).every(checkPoints)
break
case 'some':
// `hit` will be true only if some points are touching
sprite.collisionPoints = this.getPoints(sprite)
collision.hit = Object.keys(sprite.collisionPoints).some(checkPoints)
break
}
// Return the collision object.
// `collision.hit` will be true if a collision is detected.
// `collision.index` tells you the map array index number where the
// collision occured
return collision
}
// ### updateMap
/*
`updateMap` takes a map array and adds a sprite's grid index number (`gid`) to it.
It finds the sprite's new index position, and retuns the new map array.
You can use it to do very efficient collision detection in tile based game worlds.
`updateMap` arguments:
array, singleSpriteOrArrayOfSprites, worldObject
The `world` object (the 4th argument) has to have these properties:
`tileheight`, `tilewidth`, `widthInTiles`.
The sprite objects have to have have these properties:
`centerX`, `centerY`, `index`, `gid` (The number in the array that represpents the sprite)
Here's an example of how you could use `updateMap` in your game code like this:
blockLayer.data = updateMap(blockLayer.data, blockLayer.children, world);
The `blockLayer.data` array would now contain the new index position numbers of all the
child sprites on that layer.
*/
updateMap(mapArray, spritesToUpdate, world) {
// First create a map a new array filled with zeros.
// The new map array will be exactly the same size as the original
const newMapArray = mapArray.map((gid) => {
gid = 0
return gid
})
// Is `spriteToUpdate` an array of sprites?
if (spritesToUpdate instanceof Array) {
// Get the index number of each sprite in the `spritesToUpdate` array
// and add the sprite's `gid` to the matching index on the map
const self = this
spritesToUpdate.forEach((sprite) => {
// Find the new index number
sprite.index = self.getIndex(
sprite.centerX,
sprite.centerY,
world.tilewidth,
world.tileheight,
world.widthInTiles
)
// Add the sprite's `gid` number to the correct index on the map
newMapArray[sprite.index] = sprite.gid
})
}
// Is `spritesToUpdate` just a single sprite?
else {
const sprite = spritesToUpdate
// Find the new index number
sprite.index = this.getIndex(
sprite.centerX,
sprite.centerY,
world.tilewidth,
world.tileheight,
world.widthInTiles
)
// Add the sprite's `gid` number to the correct index on the map
newMapArray[sprite.index] = sprite.gid
}
// Return the new map array to replace the previous one
return newMapArray
}
/*
###makeTiledWorld
`makeTiledWorld` is a quick and easy way to display a game world designed in
Tiled Editor. Supply `makeTiledWorld` with 1 **string** argument for map json:
1. A JSON file generated by Tiled Editor.
2. A source image that represents the tile set you used to create the Tiled Editor world.
```js
let world = makeTiledWorld("tiledEditorMapData.json");
```
(Note: `makeTiledWorld` looks for the JSON data file in Pixi's `loader.resources` object. So,
make sure you've loaded the JSON file using Pixi's `loader`.)
`makeTiledWorld` will return a Pixi `Container` that contains all the things in your Tiled Editor
map as Pixi sprites.
All the image tiles you create in Tiled Editor are automatically converted into Pixi sprites
for you by `makeTiledWorld`. You can access all of them using two methods: `getObject` (for
single sprites) and `getObjects` (with an "s") for multiple sprites. Let's find out how they work.
####world.getObject
Tile Editor lets you assign a "name" properties any object.
You can access any sprite by this name using the `getObject` method. `getObject` searches for and
returns a sprite in the `world` that has the same `name` property that you assigned
in Tiled Editor. Here's how to use `getObject` to look for an object called "alien"
in the Tiled map data and assign it to a variable called `alien`
```js
let alien = world.getObject("alien");
```
`alien` is now an ordinary Pixi sprite that you can control just like any other Pixi
sprite in your games.
#### Creating sprites from generic objects
Tiled Editor lets you create generic objects. These are objects that don't have images associated
with them. Generic objects are handy to use, because they let you create complex game objects inside
Tiled Editor, as pure data. You can then use that data your game code to build complex game objects.
For example, imagine that you want to create a complex animated walking sprite called "elf".
First, create the elf object in Tiled Editor as a generic object, but don't assign any image tiles
to it. Next, in your game code, create a new Pixi MovieClip called `elf` and give it any textures you want
to use for its animation states.
```js
//Create a new Pixi MovieClip sprite
let elf = new PIXI.MovieClip(elfSpriteTextures);
```
Then use the `x` and `y` data from the generic "elf" object you created in Tiled Editor to position the
`elf` sprite.
```js
elf.x = world.getObject("elf").x;
elf.y = world.getObject("elf").y;
```
This is a simple example, but you could make very complex data objects in Tiled Editor and
use them to build complex sprites in the same way.
####Accessing Tiled Editor layer groups
Tiled Editor lets you create **layer groups**. Each layer group you create
in Tiled Editor is automatically converted by `makeTiledWorld` into a Pixi `Container`
object. You can access those containers using `getObject` to extract the layer group
container.
Here's how you could extract the layer group called "objects" and add the
`elf` sprite to it.
```js
let objectsLayer = world.getObject("objects");
objectsLayer.addChild(elf);
```
If you want to add the sprite to a different world layer, you can do it like this:
```js
world.getObject("treeTops").addChild(elf);
```
If you want to access all the sprites in a specific Tiled Editor layer, just supply
`getObject` with the name of the layer. For example, if the layer name is "items", you
can access it like this:
```js
let itemsLayer = world.getObject("items");
```
`itemsLayer` is now a Pixi container with a `children` array that contains all the sprites
on that layer.
To be safe, clone this array to create a new version
that doesn't point to the original data file:
```js
items = itemsLayer.children.slice(0);
```
You can now manipulate the `items` array freely without worrying about changing
the original array. This can possibly help prevent some weird bugs in a complex game.
###Finding the "gid" values
Tiled Editor uses "gid" numbers to identify different kinds of things in the world.
If you ever need to extract sprites with specific `gid` numbers in a
layer that contains different kinds of things, you can do it like this:
```js
let items = itemsLayer.children.map(sprite => {
if (sprite.gid !== 0) return sprite;
});
```
Every sprite created by `makeTiledWorld` has a `gid` property with a value that matches its
Tiled Editor "gid" value.
####Accessing a layer's "data" array
Tiled Editor's layers have a `data` property
that is an array containing all the grid index numbers (`gid`) of
the tiles in that array. Imagine that you've got a layer full of similar
tiles representing the walls in a game. How do you access the array
containing all the "gid" numbers of the wall sprites in that layer? If the layer's name is called "wallLayer", you
can access the `wallLayer`'s `data` array of sprites like this:
```js
wallMapArray = world.getObject("wallLayer").data;
```
`wallMapArray` is now an array of "gid" numbers referring to all the sprites on that
layer. You can now use this data for collision detection, or doing any other kind
of world building.
###world.getObjects
There's another method called `getObjects` (with an "s"!) that lets you extract
an array of sprites from the Tiled Editor data. Imagine that you created three
game objects in Tiled Editor called "marmot", "skull" and "heart". `makeTiledWorld`
automatically turns them into sprites, and you can access
all of them as array of sprites using `getObjects` like this:
```js
let gameItemsArray = world.getObjects("marmot", "skull", "heart");
```
*/
makeTiledWorld(tiledMap) {
// Create a group called `world` to contain all the layers, sprites
// and objects from the `tiledMap`. The `world` object is going to be
// returned to the main game program
const tilesets = tiledMap.tilesets
.sort((a, b) => a.firstgid - b.firstgid)
.reverse()
const tilesetsImages = tilesets.map(({ image }) => {
const { texture } =
Object.values(this.resources).find(({ name }) => name === image) || {}
return texture
})
const world = new this.Container()
const getTilesetForGid = (gid) => {
const index = tilesets.findIndex(({ firstgid }) => gid >= firstgid)
return {
tileset: tilesets[index],
image: tilesetsImages[index]
}
}
world.tileheight = tiledMap.tileheight
world.tilewidth = tiledMap.tilewidth
// Calculate the `width` and `height` of the world, in pixels
world.worldWidth = tiledMap.width * tiledMap.tilewidth
world.worldHeight = tiledMap.height * tiledMap.tileheight
// Get a reference to the world's height and width in
// tiles, in case you need to know this later (you will!)
world.widthInTiles = tiledMap.width
world.heightInTiles = tiledMap.height
// Create an `objects` array to store references to any
// named objects in the map. Named objects all have
// a `name` property that was assigned in Tiled Editor
world.objects = []
// Loop through all the map layers
tiledMap.layers.forEach((tiledLayer) => {
// Make a group for this layer and copy
// all of the layer properties onto it.
const layerGroup = new this.Container()
Object.keys(tiledLayer).forEach((keyFrom) => {
// Add all the layer's properties to the group, except the
// width and height (because the group will work those our for
// itself based on its content).
if (!['width', 'height'].includes(keyFrom)) {
const keyInto = keyFrom === 'name' ? 'label' : keyFrom
layerGroup[keyInto] = tiledLayer[keyFrom]
}
})
// Set the width and height of the layer to
// the `world`'s width and height
// layerGroup.width = world.width;
// layerGroup.height = world.height;
// Translate `opacity` to `alpha`
layerGroup.alpha = tiledLayer.opacity
// Add the group to the `world`
world.addChild(layerGroup)
// Push the group into the world's `objects` array
// So you can access it later
world.objects.push(layerGroup)
// Is this current layer a `tilelayer`?
if (tiledLayer.type === 'tilelayer') {
// Loop through the `data` array of this layer
tiledLayer.data.forEach((gid, index) => {
let tileSprite
let tilesetX
let tilesetY
// If the grid id number (`gid`) isn't zero, create a sprite
if (gid !== 0) {
const { tileset, image } = getTilesetForGid(gid)
// The optional spacing (padding) around each tile
// This is to account for spacing around tiles
// that's commonly used with texture atlas tilesets. Set the
// `spacing` property when you create a new map in Tiled Editor
const spacing = tileset.spacing
// Figure out how many columns there are on the tileset.
// This is the width of the image, divided by the width
// of each tile, plus any optional spacing thats around each tile
const numberOfTilesetColumns = Math.floor(
tileset.imagewidth / (tiledMap.tilewidth + spacing)
)
// Figure out the map column and row number that we're on, and then
// calculate the grid cell's x and y pixel position.
const mapColumn = index % world.widthInTiles
const mapRow = Math.floor(index / world.widthInTiles)
const mapX = mapColumn * world.tilewidth
const mapY = mapRow * world.tileheight
// Figure out the column and row number that the tileset
// image is on, and then use those values to calculate
// the x and y pixel position of the image on the tileset
const tilesetColumn =
(gid - tileset.firstgid) % numberOfTilesetColumns
const tilesetRow = Math.floor(
(gid - tileset.firstgid) / numberOfTilesetColumns
)
tilesetX = tilesetColumn * world.tilewidth
tilesetY = tilesetRow * world.tileheight
// Compensate for any optional spacing (padding) around the tiles if
// there is any. This bit of code accumlates the spacing offsets from the
// left side of the tileset and adds them to the current tile's position
if (spacing > 0) {
tilesetX +=
spacing +
spacing * ((gid - tileset.firstgid) % numberOfTilesetColumns)
tilesetY +=
spacing +
spacing *
Math.floor((gid - tileset.firstgid) / numberOfTilesetColumns)
}
// Use the above values to create the sprite's image from
// the tileset image
const texture = this.frame(
image,
tilesetX,
tilesetY,
world.tilewidth,
world.tileheight
)
// I've dedcided that any tiles that have a `name` property are important
// and should be accessible in the `world.objects` array.
const tileproperties = tileset.tileproperties || {}
const key = String(gid - tileset.firstgid)
// If the JSON `tileproperties` object has a sub-object that
// matches the current tile, and that sub-object has a `name` property,
// then create a sprite and assign the tile properties onto
// the sprite
if (tileproperties[key] && tileproperties[key].label) {
// Make a sprite
tileSprite = new this.Sprite(texture)
// Copy all of the tile's properties onto the sprite
// (This includes the `name` property)
Object.keys(tileproperties[key]).forEach((property) => {
// console.log(tileproperties[key][property])
tileSprite[property] = tileproperties[key][property]
})
// Push the sprite into the world's `objects` array
// so that you can access it by `name` later
world.objects.push(tileSprite)
}
// If the tile doesn't have a `name` property, just use it to
// create an ordinary sprite (it will only need one texture)
else {
tileSprite = new this.Sprite(texture)
}
// Position the sprite on the map
tileSprite.x = mapX
tileSprite.y = mapY
// Make a record of the sprite's index number in the array
// (We'll use this for collision detection later)
tileSprite.index = index
// Make a record of the sprite's `gid` on the tileset.
// This will also be useful for collision detection later
tileSprite.gid = gid
// Add the sprite to the current layer group
layerGroup.addChild(tileSprite)
}
})
}
// Is this layer an `objectgroup`?
if (tiledLayer.type === 'objectgroup') {
tiledLayer.objects.forEach((object) => {
// We're just going to capture the object's properties
// so that we can decide what to do with it later
// Get a reference to the layer group the object is in
object.group = layerGroup
// Because this is an object layer, it doesn't contain any
// sprites, just data object. That means it won't be able to
// calucalte its own height and width. To help it out, give
// the `layerGroup` the same `width` and `height` as the `world`
// layerGroup.width = world.width;
// layerGroup.height = world.height;
// Push the object into the world's `objects` array
world.objects.push(object)
})
}
})
// Search functions
// `world.getObject` and `world.getObjects` search for and return
// any sprites or objects in the `world.objects` array.
// Any object that has a `name` propery in
// Tiled Editor will show up in a search.
// `getObject` gives you a single object, `getObjects` gives you an array
// of objects.
// `getObject` returns the actual search function, so you
// can use the following format to directly access a single object:
// sprite.x = world.getObject("anySprite").x;
// sprite.y = world.getObject("anySprite").y;
world.getObject = (objectName) => {
const searchForObject = () => {
let foundObject
world.objects.some((object) => {
if (object.label === objectName) {
foundObject = object
return true
}
})
if (foundObject) {
return foundObject
}
throw new Error(
`There is no object with the property name: ${objectName}`
)
}
// Return the search function
return searchForObject()
}
world.getObjects = (objectNames) => {
const foundObjects = []
world.objects.forEach((object) => {
if (object.label && objectNames.indexOf(object.label) !== -1) {
foundObjects.push(object)
}
})
if (foundObjects.length > 0) {
return foundObjects
}
throw new Error('I could not find those objects')
}
// That's it, we're done!
// Finally, return the `world` object back to the game program
return world
}
/* Isometric tile utilities */
/*
### byDepth
And array `sort` function that depth-sorts sprites according to
their `z` properties
*/
byDepth(a, b) {
// Calculate the depths of `a` and `b`
// (add `1` to `a.z` and `b.x` to avoid multiplying by 0)
a.depth = (a.cartX + a.cartY) * (a.z + 1)
b.depth = (b.cartX + b.cartY) * (b.z + 1)
// Move sprites with a lower depth to a higher position in the array
if (a.depth < b.depth) {
return -1
} else if (a.depth > b.depth) {
return 1
}
return 0
}
/*
### hitTestIsoTile
Same API as `hitTestTile`, except that it works with isometric sprites.
Make sure that your `world` object has properties called
`cartTileWidth` and `cartTileHeight` that define the Cartesian with and
height of your tile cells, in pixels.
*/
hitTestIsoTile(sprite, mapArray, gidToCheck, world, pointsToCheck) {
// The `checkPoints` helper function Loop through the sprite's corner points to
// find out if they are inside an array cell that you're interested in.
// Return `true` if they are
const checkPoints = (key) => {
// Get a reference to the current point to check.
// (`topLeft`, `topRight`, `bottomLeft` or `bottomRight` )
const point = sprite.collisionPoints[key]
// Find the point's index number in the map array
collision.index = this.getIndex(
point.x,
point.y,
world.cartTilewidth,
world.cartTileheight,
world.widthInTiles
)
// Find out what the gid value is in the map position
// that the point is currently over
collision.gid = mapArray[collision.index]
// If it matches the value of the gid that we're interested, in
// then there's been a collision
if (collision.gid === gidToCheck) {
return true
}
return false
}
// Assign "some" as the default value for `pointsToCheck`
pointsToCheck = pointsToCheck || 'some'
// The collision object that will be returned by this function
const collision = {}
// Which points do you want to check?
// "every", "some" or "center"?
switch (pointsToCheck) {
case 'center':
// `hit` will be true only if the center point is touching
sprite.collisionPoints = {
center: {
x: sprite.centerX,
y: sprite.centerY
// x: s.cartX + ca.x + (ca.width / 2),
// y: s.cartY + ca.y + (ca.height / 2)
}
}
collision.hit = Object.keys(sprite.collisionPoints).some(checkPoints)
break
case 'every':
// `hit` will be true if every point is touching
sprite.collisionPoints = this.getIsoPoints(sprite)
collision.hit = Object.keys(sprite.collisionPoints).every(checkPoints)
break
case 'some':
// `hit` will be true only if some points are touching
sprite.collisionPoints = this.getIsoPoints(sprite)
collision.hit = Object.keys(sprite.collisionPoints).some(checkPoints)
break
}
// Return the collision object.
// `collision.hit` will be true if a collision is detected.
// `collision.index` tells you the map array index number where the
// collision occured
return collision
}
/*
### getIsoPoints
The isomertic version of `getPoints`
*/
getIsoPoints(s) {
const ca = s.collisionArea
if (ca !== undefined) {
return {
topLeft: {
x: s.cartX + ca.x,
y: s.cartY + ca.y
},
topRight: {
x: s.cartX + ca.x + ca.width,
y: s.cartY + ca.y
},
bottomLeft: {
x: s.cartX + ca.x,
y: s.cartY + ca.y + ca.height
},
bottomRight: {
x: s.cartX + ca.x + ca.width,
y: s.cartY + ca.y + ca.height
}
}
}
return {
topLeft: {
x: s.cartX,
y: s.cartY
},
topRight: {
x: s.cartX + s.cartWidth - 1,
y: s.cartY
},
bottomLeft: {
x: s.cartX,
y: s.cartY + s.cartHeight - 1
},
bottomRight: {
x: s.cartX + s.cartWidth - 1,
y: s.cartY + s.cartHeight - 1
}
}
}
/*
### makeIsoPointer
Used to add a isometric properties to any mouse/touch `pointer` object with
`x` and `y` properties. Supply `makeIsoPointer` with the pointer object and
the isometric `world` object
*/
// Create some useful properties on the pointer
makeIsoPointer(pointer, world) {
Object.defineProperties(pointer, {
// The isometric's world's Cartesian coordiantes
cartX: {
get() {
const x =
(2 * this.y + this.x - (2 * world.y + world.x)) / 2 -
world.cartTilewidth / 2
return x
},
enumerable: true,
configurable: true
},
cartY: {
get() {
const y =
(2 * this.y - this.x - (2 * world.y - world.x)) / 2 +
world.cartTileheight / 2
return y
},
enumerable: true,
configurable: true
},
// The tile's column and row in the array
column: {
get() {
return Math.floor(this.cartX / world.cartTilewidth)
},
enumerable: true,
configurable: true
},
row: {
get() {
return Math.floor(this.cartY / world.cartTileheight)
},
enumerable: true,
configurable: true
},
// The tile's index number in the array
index: {
get() {
const index = {}
// Convert pixel coordinates to map index coordinates
index.x = Math.floor(this.cartX / world.cartTilewidth)
index.y = Math.floor(this.cartY / world.cartTileheight)
// Return the index number
return index.x + index.y * world.widthInTiles
},
enumerable: true,
configurable: true
}
})
}
/*
### isoRectangle
A function for creating a simple isometric diamond
shaped rectangle using Pixi's graphics library
*/
isoRectangle(width, height, fillStyle) {
// Figure out the `halfHeight` value
const halfHeight = height / 2
// Draw the flattened and rotated square (diamond shape)
const rectangle = new this.Graphics()
rectangle.beginFill(fillStyle)
rectangle.moveTo(0, 0)
rectangle.lineTo(width, halfHeight)
rectangle.lineTo(0, height)
rectangle.lineTo(-width, halfHeight)
rectangle.lineTo(0, 0)
rectangle.endFill()
// Generate a texture from the rectangle
const texture = rectangle.generateTexture()
// Use the texture to create a sprite
const sprite = new this.Sprite(texture)
// Return it to the main program
return sprite
}
/*
### addIsoProperties
Add properties to a sprite to help work between Cartesian
and isometric properties: `isoX`, `isoY`, `cartX`,
`cartWidth` and `cartHeight`.