This repository has been archived by the owner on Aug 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 39
/
index.html
1568 lines (1245 loc) · 67.3 KB
/
index.html
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
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>melonJS - Platformer Tutorial</title>
<meta name="description" content="melonJS Tutorial">
<meta name="keywords"
content="melonJS, lightweight, HTML5 game engine, HTML5, javascript, canvas, game, engine, framework, tiled, tile, map, loader, parser, TMX, XML, tutorial">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="vendor/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="vendor/prism.css">
<link rel="stylesheet" type="text/css" href="style/style.css">
<link rel="icon" type="image/png" href="style/favicon.png">
<script type="text/javascript">
//<![CDATA[
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-13050059-3']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
//]]>
</script>
</head>
<body class="language-javascript">
<a href="https://github.com/melonjs/tutorial-platformer"><img
style="position: absolute; top: 0; right: 0; border: 0; z-index: 1000;"
src="https://camo.githubusercontent.com/e7bbb0521b397edbd5fe43e7f760759336b5e05f/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f677265656e5f3030373230302e706e67"
alt="Fork me on GitHub"
data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_green_007200.png"></a>
<div id="main">
<div class="row">
<div id="sidebar" class="col-md-2 col-md-offset-1 sidebar">
<a class="logo" href="http://www.melonjs.org/"><img src="style/melon.png" alt="melonJS"></a>
<ul class="nav nav-sidebar">
<li><h3>Content</h3></li>
<li><a href="#intro">Introduction</a></li>
<li><a href="#part1">Part 1: Creating a level using Tiled</a></li>
<li><a href="#part2">Part 2: Loading the level</a></li>
<li><a href="#part3">Part 3: Adding a main player</a></li>
<li><a href="#part4">Part 4: Adding a scrolling background</a></li>
<li><a href="#part5">Part 5: Adding some basic objects and enemies</a></li>
<li><a href="#part6">Part 6: Adding some basic HUD information</a></li>
<li><a href="#part7">Part 7: Adding some audio</a></li>
<li><a href="#part8">Part 8: Adding a second level</a></li>
<li><a href="#part9">Part 9: Adding a title screen</a></li>
<li><a href="#part10">Part 10: Conclusion</a></li>
<li><a href="#part11">Part 11: Refactoring (Optional)</a></li>
</ul>
</div>
<div id="content" class="col-md-8 col-md-offset-3 main">
<h1>Platformer Tutorial</h1>
<p>In this tutorial, we will create a simple platformer. This tutorial will primarily be focused on creating
the basic element of a working game using Tiled as the level editor.</p>
<!-- INTRO ================================================================== -->
<div>
<a id="intro" class="offset-anchor"></a>
<div class="subcontent">
<h2>Introduction</h2>
<p>To work through this tutorial, you need the following:</p>
<ul>
<li>The <a href="http://www.mapeditor.org/">Tiled Map Editor</a>, installed and running (0.9.0
or later)
</li>
<li>
The melonJS <a
href="https://github.com/melonjs/es6-boilerplate/archive/refs/heads/main.zip">boilerplate</a>, that
we will use as default template project for our tutorial (please make sure to install the required dependencies as instructed in the <a
href="https://github.com/melonjs/es6-boilerplate#readme">README</a>)
</li>
<li>
The tutorial <a href="tutorial_data.zip">data files</a>, to be uncompressed inside the (here
above) template <b>src/data</b> directory, and which contains the following :
<ul>
<li>a level tileset (area01_level_tiles.png)</li>
<li>two backgrounds for parallax layers (background.png & clouds.png)</li>
<li>some basic spritesheets (player & enemey animation spritesheet, spinning coin)</li>
<li>some audio sfx and music (in both mp3 and ogg format)</li>
<li>a title screen background (title_screen.png)</li>
</ul>
</li>
<li>The melonJS <a href="http://melonjs.github.io/melonJS/docs/">documentation</a> for more
details
</li>
</ul>
<p>
<b>Testing/debugging :</b><br/>
If you just want to use the filesystem, the problem is you'll run into "cross-origin request"
security errors. With Chrome, you need to use the "--disable-web-security" parameter or better
"--allow-file-access-from-files" when launching the browser. This must be done in order to test
any local content, else the browser will complain when trying to load assets through XHR.
<strong>Though this method is not recommended, </strong> since as long as you have the option
enabled, you're adding security vulnerabilities to your environmnet.
</p>
<p> A second and easier option is to use a local web server, as for example detailed in the melonJS
boilerplate <a href="https://github.com/melonjs/es6-boilerplate#readme">README</a>, by using the <b>npm run dev</b>
tool, and that will allow you to test your game in your browser.</p>
<p class="c1">Additional Credits :</p>
<ul>
<li>
<a href="http://www.spicypixel.net/2008/01/10/gfxlib-fuzed-a-free-developer-graphic-library/">SpicyPixel.NET</a>
for the GfxLib-Fuzed assets
</li>
<li><a href="http://www.nosoapradio.us/">noSoapRadio</a> for the in game music</li>
</ul>
<p>
Feel free to modify whatever you want. We also assume here, that you are already familiar with
Tiled; if you need more help with the tool, you can check the Tiled homepage and <a
href="https://github.com/bjorn/tiled/wiki">wiki</a> for further help.
</p>
</div>
</div>
<!-- PART 1 ======================================================================= -->
<div>
<a id="part1" class="offset-anchor"></a>
<div class="subcontent">
<h2>Part 1: Creating a level using Tiled</h2>
<p><i>Note: Before starting, and if you are new to Tiled, we strongly encourage you to read this introduction <a
href="https://doc.mapeditor.org/en/stable/manual/introduction/">here</a>,
that provides the basic on how to get started and how the editor is working.</i></p>
<p>First let's open Tiled and create a new map : for this tutorial we will we use a 640x480 canvas,
and since we have 32x32 tiles, we must specify at least 20 and 15 for the map size. In my
example I'll define a <b>40x15</b> level, so we can play with scrolling background later.</p>
<img src="media/step1_newmap.png" alt="Step 1 of creating a new map"/>
<p>Also, as melonJS supports only <i><b>uncompressed</b></i> tilemaps, please be sure that your
settings are correct. We do recommend the Base64 encoding, since it produces a smaller file, but
it's really up to you.</p>
<p>Then let's add our tileset using Map/New Tileset. Be sure to configure the tileset spacing and
margin to zero in tiled.</p>
<img src="media/step1_newtileset.png" alt="Adding a tileset"/>
<p>For the beauty of it, we will create two layers - one background layer, and one foreground layer.
Feel free to use your imagination and do whatever you want. I named them logically "background"
and "foreground", but you can put whatever you want.</p>
<p>Here's what my level looked like when I finished it : <img
src="media/step1_tiled_level_design.png" alt="Tiled level design"/></p>
<p>Finally, let's define a background color for our level, by using the color picker tool (Map/Map
Properties), and just specify any color you prefer.</p>
<img src="media/step1_background_color.png" alt="Setting a background color in Tiled"/>
<p>To finish, let's save our new map as "area01" under the "src/data/map/" folder, and we are done with the first step!</p>
</div>
</div>
<!-- PART 2 ======================================================================== -->
<div>
<a id="part2" class="offset-anchor"></a>
<div class="subcontent">
<h2>Part 2: Loading our level</h2>
<p>First of all, and after unzipping the tutorial assets into the boilerplate <b>"src/data"</b> directory structure,
you should have something like this:</p>
<pre>
src
└── data
│ ├── bgm
│ │ ├── dst-inertexponent.mp3
│ │ └── dst-inertexponent.ogg
│ ├── fnt
│ │ ├── PressStart2P.png
│ │ └── PressStart2P.fnt
| ├── img
| | ├── gui
| │ │ └── title_screen.png
| | ├── map
| │ │ └── area01_level_tiles.png
| | ├── sprite
| │ │ ├── gripe_run_right.png
| │ │ ├── spinning_coin_gold.png
| │ │ └── wheelie_right.png
│ │ ├── background.png
│ │ └── clouds.png
| ├── map
| ├── sfx
│ │ ├── cling.mp3
│ │ ├── cling.ogg
│ │ ├── jump.mp3
│ │ ├── jump.ogg
│ │ ├── stomp.mp3
│ │ └── stomp.ogg
└── js
| ├── renderables
| └── stage
├── index.js
├── index.css
├── index.html
└── manifest.js
</pre>
<p>The boilerplate also provides a bunch of default code, but first let's have a look first at our index.js file:</p>
<pre><code>
import * as me from 'melonjs/dist/melonjs.module.js';
import TitleScreen from './js/stage/title.js';
import PlayScreen from './js/stage/play.js';
import PlayerEntity from "./js/renderables/player-entity.js";
import CoinEntity from "./js/renderables/coin-entity.js";
import EnemyEntity from "./js/renderables/enemy-entity.js";
import DataManifest from './manifest.js';
/* Game namespace */
me.device.onReady(() => {
// Initialize the video.
if (!me.video.init(640, 480, {parent : "screen", scale : "auto"})) {
alert("Your browser does not support HTML5 canvas.");
return;
}
// initialize the debug plugin in development mode.
import('./js/plugin/debug/debugPanel.js').then((plugin) => {
// automatically register the debug panel
me.utils.function.defer(me.plugin.register, this, plugin.DebugPanelPlugin, "debugPanel");
});
// Initialize the audio.
me.audio.init("mp3,ogg");
// allow cross-origin for image/texture loading
me.loader.crossOrigin = "anonymous";
// set and load all resources.
me.loader.preload(DataManifest, function() {
// set the user defined game stages
me.state.set(me.state.MENU, new TitleScreen());
me.state.set(me.state.PLAY, new PlayScreen());
// set a global fading transition for the screen
me.state.transition("fade", "#FFFFFF", 250);
// add our player entity in the entity pool
me.pool.register("mainPlayer", PlayerEntity);
me.pool.register("CoinEntity", CoinEntity);
me.pool.register("EnemyEntity", EnemyEntity);
// enable the keyboard
me.input.bindKey(me.input.KEY.LEFT, "left");
me.input.bindKey(me.input.KEY.RIGHT, "right");
// map X, Up Arrow and Space for jump
me.input.bindKey(me.input.KEY.X, "jump", true);
me.input.bindKey(me.input.KEY.UP, "jump", true);
me.input.bindKey(me.input.KEY.SPACE, "jump", true);
// Start the game.
me.state.change(me.state.MENU);
});
});
</code></pre>
<p>This is very simple. Once the page is loaded, the display and audio is initialized, and set all game resources to be preloaded.
Once done, we define a new state that will be used for the in game stuff, together with a <a
href="http://melonjs.github.io/melonJS/docs/me.Stage.html"> <b>PlayScreen</b> Stage object</a>
that we will use to manage the game event (reset, etc...).</p>
<p>The only change we will do here for now is chaging the given video resolution for the
`me.video.init()` function, as for the tutorial we will create a 640x480 canvas.
Also we will change the <b>scaleMethod</b> to <b>"flex-width"</b>, as it better fits with a
platformer game (see the <a href="http://melonjs.github.io/melonJS/docs/me.video.html#init">`me.video.init`</a>
documentation for further information on the various scaling mode available).</p>
<p>Then we need to actually add both the TMX level we created in the first step together with its tileset
to the list of assets to load in the data manifest by add the two below lines to the <b>manifest.js</b> file (full format described <a
href="https://github.com/melonjs/melonJS/wiki/resources">here</a>).
<pre><code>{name: "area01_level_tiles", type:"image", src: "data/img/map/area01_level_tiles.png"},
{name: "area01", type: "tmx", src: "data/map/area01.tmx"}
</code></pre>
<p>Note that although we use here directly the tmx file, for production we do recommend using
the json format (that can also be exported directly from Tiled), as it gives a smaller file
size, allows for much faster level loading and prevents from any server issue with the .tmx
extension. </p>
<p>Also please do note that here we import melonJS using the <b>'melonjs/dist/melonjs.module.js'</b> path,
under the assumption that you use the boilerplate. If however you prefer using a CDN network for delivery
you can use <b>'https://esm.run/melonjs'</b> or any other format or version provided through <a
href="https://www.jsdelivr.com/package/npm/melonjs">jsDelivr</a></p>.
<p>Finally, let's open the ./js/stage/play.js file and in the <a
href="http://melonjs.github.io/melonJS/docs/me.Stage.html#onResetEvent">onResetEvent()</a>
function (which is called on a state change), we use the level <a
href="http://melonjs.github.io/melonJS/docs/me.level.html#.load">load function</a> to
display our previously preloaded level, using our default level name :</p>
<pre><code>
import * as me from 'melonjs/dist/melonjs.module.js';
import HUD from '../renderables/hud/container.js'
import data from '../data.js'
export default class PlayScreen extends me.Stage {
/**
* action to perform on state change
*/
onResetEvent() {
// load a level
me.level.load("area01");
// reset the score
data.score = 0;
// add our HUD to the game world
this.HUD = new HUDContainer();
me.game.world.addChild(this.HUD);
}
/**
* action to perform when leaving this screen (state change)
*/
onDestroyEvent() {
// remove the HUD from the game world
me.game.world.removeChild(this.HUD);
}
}
</code></pre>
<p>That's all! If you did everything correctly, and open your index.html (Remember that if you don’t
use a web server, you will need to allow your browser to access local files, please refer to the
“Testing/debugging” at the beginning of the tutorial if required).</p>
<h3>Try it out</h3>
<p>(click on the image to see it running in your browser), you should see something like this</p>
<a href="./tutorial_step2/index.html" target="_blank"><img src="media/tutorial_step2.png"
alt="Step 2 results"/></a>
<p>Yes, nothing fancy yet, but that's only the beginning!</p>
<p>Also in case you didn't notice, since we defined a 640x480 display in our application, we only
see a part of the map (the half of it to be exact), which is normal. <b>melonJS</b>
automatically creates a corresponding viewport, and we will be able to navigate through the map
in the next step, when we will add a "main player"</p>
</div>
</div> <!-- end part 2 -->
<!-- PART 3 ================================================================================= -->
<div>
<a id="part3" class="offset-anchor"></a>
<div class="subcontent">
<h2>Part 3: Add a main player</h2>
<p>Here we will create a new object by extending the default <a
href="http://melonjs.github.io/melonJS/docs/me.Entity.html"> me.Entity</a>, to create our
player. We will use the provided simple spritesheet <b>(gripe_run_right.png)</b> to animate our
character, and define a basic walking and standing animation. It's of course possible to define
more complex animations for the same entity (jumping, crouching, when hurt, etc...), but let's
keep things simple for now.</p>
<img src="media/gripe_run_right.png" alt="Gripe run right"/>
<p>Then it's time to create our entity, open the `./js/renderables/player.js` example file, and let's
complete it to match with the following : </p>
<pre><code>
import * as me from 'melonjs/dist/melonjs.module.js';
/**
* Player Entity
*/
export default class PlayerEntity extends me.Entity {
/**
*
* @param x
* @param y
* @param settings
*/
constructor(x, y, settings) {
super(x, y, settings);
// max walking & jumping speed
this.body.setMaxVelocity(3, 15);
this.body.setFriction(0.4, 0);
// set the display to follow our position on both axis
me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH, 0.4);
// ensure the player is updated even when outside of the viewport
this.alwaysUpdate = true;
// define a basic walking animation (using all frames)
this.renderable.addAnimation("walk", [0, 1, 2, 3, 4, 5, 6, 7]);
// define a standing animation (using the first frame)
this.renderable.addAnimation("stand", [0]);
// set the standing animation as default
this.renderable.setCurrentAnimation("stand");
}
/**
* Update the Entity
*
* @param dt
* @returns {any|boolean}
*/
update(dt) {
if (me.input.isKeyPressed('left')) {
// flip the sprite on horizontal axis
this.renderable.flipX(true);
// update the default force
this.body.force.x = -this.body.maxVel.x;
// change to the walking animation
if (!this.renderable.isCurrentAnimation("walk")) {
this.renderable.setCurrentAnimation("walk");
}
} else if (me.input.isKeyPressed('right')) {
// unflip the sprite
this.renderable.flipX(false);
// update the entity velocity
this.body.force.x = this.body.maxVel.x;
// change to the walking animation
if (!this.renderable.isCurrentAnimation("walk")) {
this.renderable.setCurrentAnimation("walk");
}
} else {
// change to the standing animation
this.renderable.setCurrentAnimation("stand");
}
if (me.input.isKeyPressed('jump')) {
if (!this.body.jumping && !this.body.falling)
{
// set current vel to the maximum defined value
// gravity will then do the rest
this.body.force.y = -this.body.maxVel.y
}
} else {
this.body.force.y = 0;
}
return (super.update(dt) || this.body.vel.x !== 0 || this.body.vel.y !== 0);
}
/**
* Collision Handler
*
* @returns {boolean}
*/
onCollision() {
return true;
}
}
</code></pre>
<p>I think the above code is quite easy to understand. Basically, we extend the <a
href="http://melonjs.github.io/melonJS/docs/me.Entity.html"> Entity</a>, configure the
default player speed, tweak the camera, test if some keys are pressed and manage our player
movement (by setting the player speed).
Also, you may notice that I'm testing the final velocity (this.body.vel.x and this.body.vel.y)
of my object, which allows me to know if my object actually moved, and control if I want the
sprite animation to run or not.</p>
<p>Then, although the default game.PlayerEntity is already declare in the boilerplate, we have to
modify our "main" to actually declare our new entity in the object <a
href="http://melonjs.github.io/melonJS/docs/me.pool.html"> pool</a> (that is used by the
engine to instantiate object), and finally to map the keys we will use for the player movement.
So our <b>loaded()</b> function will become:</p>
<pre><code>// Run on game resources loaded.
loaded() {
me.state.set(me.state.MENU, new TitleScreen());
me.state.set(me.state.PLAY, new PlayScreen());
// add our player entity in the entity pool
me.pool.register("mainPlayer", PlayerEntity);
// enable the keyboard
me.input.bindKey(me.input.KEY.LEFT, "left");
me.input.bindKey(me.input.KEY.RIGHT, "right");
// map X, Up Arrow and Space for jump
me.input.bindKey(me.input.KEY.X, "jump", true);
me.input.bindKey(me.input.KEY.UP, "jump", true);
me.input.bindKey(me.input.KEY.SPACE, "jump", true);
// Start the game.
me.state.change(me.state.PLAY);
}
</code></pre>
<p>And now we can add our entity into the level! Go back to Tiled, add a new Object Layer, and
finally a new Entity. To create a new Entity use the "Insert Rectangle" Tool to add a rectangle
to the object layer, then you can right click the object and add the properties below.</p>
<p>Name it (case does not matter) <b>mainPlayer</b> (or using the same name you used when
registering our Object into the Object Pool), and add two properties to the Object:</p>
<ul>
<li><b>image</b> : with the <b>gripe_run_right</b> value (name of our resource</li>
<li><b>framewidth</b> : with the value <b>64</b> which is the size of a single sprite in the
spritesheet
</li>
<li><b>frameheight</b> : we don't define this value here since we use a single line spritesheet,
and since in this case the engine will take the actual image height as a value for it.
</li>
</ul>
<p>These two parameters will be passed as settings parameters (to the constructor) when the object will be created.
Now you can either specify these fields here in Tiled, or directly in your code (when dealing with multiple
objects, it can be easier to just specify the name in Tiled, and manage the rest in the
constructor directly).</p>
<p>Note: You also free to add as many properties as you want, they will all be available in the
settings object passed to your constructor.</p>
<img src="media/step3_addEntity.png" alt="Adding an entity"/>
<p> Once the object is created just positionate your entity in the level, and as in the below
example make sure you are also resizing the object rectangle in Tiled to match with your actual
sprite size.</p>
<img src="media/step3_object_position.png" alt="positioning an entity"/>
<h3>Define the collision layer</h3>
<p> We are almost done! The last step is to define the collision layer. For this we simply need to
create a new object layer named "collision" and add some basic shapes to it. That's all it
takes!</p>
<p> So now add a new Object Group Layer. This layer's name <b>MUST contain the keyword
"collision"</b> for the engine to recognize it as a collision object layer.</p>
<p> Once the layer is added, select it, and just "draw" your level collision map by adding any shape
using the object toolbar</p>
<img src="media/step3_toolbar.png" alt="object tool bar"/>
<p> Please note that melonJS implements collision detection using the Separating Axis Theorem
algorithm. All polygons used for collision are required to be <i>convex</i> with all vertices
defined with clockwise winding. A polygon is convex when all line segments connecting two points
in the interior do not cross any edge of the polygon (which means that all angles are less than
180 degrees), as shown here below:</p>
<img src="media/convex_polygon.png"/>
<p>A polygon's "winding" is clockwise iff its vertices (points) are declared turning to the right
(Secondary note: The image above shows COUNTERCLOCKWISE winding.)</p>
<p> Also if you need complex shapes to specify the parimeter of the environment, then it is
recommended to use separate line segments. Lines can also be used for example when defining
platform or wall elements, where you only need a specific side of the object to be
collidable</p>
<h3>Try it out</h3>
<p> Save everything, and if you now re-open your index.html, you should see something like this:
(click on the image to see it running in your browser)</p>
<a href="./tutorial_step3/index.html" target="_blank"><img src="media/tutorial_step3.png"
alt="Step 3 Results"/></a>
<p>You will also notice that the display is automatically following our player, scrolling the
environment.</p>
<p> One last thing - when creating an object, a default collision shape is automatically created to
manage collision between objects, based on the object size you defined in Tiled. For debugging
purposes, you can enable the debug panel by adding <b>#debug</b> to URL in the browser URL bar.
</p>
<p>If you reload the game, and enable "hitbox" you will see this:</p>
<img src="media/step3_debugpanel.png" alt="Enabling the debug panel"/>
<p> The collision box can be adjusted from Tiled by changing the size of the object and match the
above example. (Collision Shape can also manually adjusted by accessing the entity body <a
href="http://melonjs.github.io/melonJS/docs/me.Body.html#shapes">shapes</a> property).
</p>
<p>Note : When using the debug Panel, the sprite border is drawn in green, the defined collision
shape(s) is/are drawn in red, and if you use something else/more than a rectangular collision
shape, you should also see an orange box that is corresponding to the smallest rectangle
containing all the defined collision shapes (and also called the entity body bounding box).</p>
</div>
</div> <!-- end part 3 -->
<!-- PART 4 =========================================================================== -->
<div>
<a id="part4" class="offset-anchor"></a>
<div class="subcontent">
<h2>Part 4: Add a scrolling background</h2>
<p>This one is very easy. We don't even have to add a single line of code, since everything is done
through Tiled.</p>
<p>First, remove the background color that we added previously at the end of Part 1. (to do so, you
will need to text edit the TMX file and remove the `backgroundcolor` property). Since the
background will be filled with our scrolling layers, we don't need the display to be cleared
with a specific color (furthermore it will save some precious frames).</p>
<p>Then we will use the two following backgrounds:</p>
<p><b>src/data/img/background.png</b> for the first background layer</p>
<img src="media/background.png" alt="Parallax background 1"/>
<p><b>src/data/img/clouds.png</b> for the second background layer</p>
<img src="media/clouds.png" alt="Parallax background 2"/>
<p>Open Tiled, and add two new <a href="http://melonjs.github.io/melonJS/docs/me.ImageLayer.html">
<b>Image Layers</b></a>, name them to whatever you like and make sure to adjust correctly the
layer order (the display order being from bottom to top) </p>
<img src="media/step4_layer.png" alt="Layering parallax layers"/>
<p>Now right-click the layers to define their properties and set the following property : </p>
<ul>
<li>Click the <b>browse</b> button and select the <b>background.png</b> image for the first
layer (<b>Parallax_layer1</b> on the picture)
</li>
<li>Do this again for the second layer (Parallax_layer2) with the <b>clouds.png</b> image</li>
</ul>
<img src="media/step4_Imagelayer_property.png" alt="Configuring Image Layer properties"/>
<p>And finally add a <a href="http://melonjs.github.io/melonJS/docs/me.ImageLayer.html#ratio"> <b>ratio</b></a>
property to specify the scrolling speed of each layer : we will specify the <b>0.25</b> value
for the first layer (<b>Parallax_layer1</b> on the picture) and the <b>0.35</b> value for the
second (keep in mind that the smaller the ratio is, the slower the scrolling speed will be).</p>
<p>Note that default behavior for Image Layer is to be automatically <a
href="http://melonjs.github.io/melonJS/docs/me.ImageLayer.html#repeat"><b>repeated</b></a>
on both x and y axis, which is exactly what we want here to create the parallax effect.</p>
<h3>Try it out</h3>
<p>"Et voila!". If you now open your index.html, you should see:</p>
<a href="./tutorial_step4/index.html" target="_blank"><img src="media/tutorial_step4.png" alt=
"Step 4 results"/></a>
<p>Play around with your player, and enjoy the view :)</p>
</div>
</div> <!-- end part 4 -->
<!-- PART 5 ======================================================================= -->
<div>
<a id="part5" class="offset-anchor"></a>
<div class="subcontent">
<h2>Part 5: Adding some basic objects and enemies</h2>
<p>In this part we will add a collectible coin (that we will use later to add to our score), using
the <b>spinning_coin_gold.png</b> spritesheet:</p>
<img src="media/spinning_coin_gold.png" alt="Spinning gold coin"/>
<p>And a basic enemy, using the <b>wheelie_right.png</b> spritesheet:</p>
<img src="media/wheelie_right.png" alt="Wheelie right sprite"/>
<p>First, we need to tell MelonJS that our PlayerEntity class has the collisionType of PLAYER_OBJECT.
Second, we need to rearrange our exports so that we have three entities in the file.</p>
<p class="alert alert-danger">In a real environment, you would have one class per file. This is a tutorial, so we're just doing it quick (and wrong!)</p>
<pre><code>//... in entities.js
let entities = {};
// allow `import {PlayerEntity} from './entities.js'`
export class PlayerEntity extends me.Entity {
constructor(x, y, settings) {
super(x, y, settings);
// ...
// we need to tell the game that this is a PLAYER_OBJECT, now that there are other entities that can collide
// with a player
this.body.collisionType = me.collision.types.PLAYER_OBJECT;
// ...
}
// ...
}
entities.PlayerEntity = PlayerEntity;
// ...
// export all the entities on the object for convenience.
// import entities from './entities.js'
export default entities;
</code></pre>
<p>The coin itself is pretty easy; we just extend the <a
href="http://melonjs.github.io/melonJS/docs/me.CollectableEntity.html">
me.Collectable</a>. Actually, we could directly use it in Tiled (without needing to create
CoinEntity here), but since we will add some score and some audio sfx later when the coin is
collected, let's do it directly this way.</p>
<pre><code>export class CoinEntity extends me.Collectable {
// extending the init function is not mandatory
// unless you need to add some extra initialization
constructor(x, y, settings) {
// call the parent constructor
super(x, y , settings);
// this item collides ONLY with PLAYER_OBJECT
this.body.setCollisionMask(me.collision.types.PLAYER_OBJECT);
}
// this function is called by the engine, when
// an object is touched by something (here collected)
onCollision(response, other) {
// do something when collected
// make sure it cannot be collected "again"
this.body.setCollisionMask(me.collision.types.NO_OBJECT);
// remove it
me.game.world.removeChild(this);
return false
}
}
entities.CoinEntity = CoinEntity;
</code></pre>
<p>Also, just to be sure it's clear for you that both ways of doing this is possible, we will define
the Coin object properties directly in Tiled, so we don't need to add anything else in the
constructor for now:</p>
<img src="media/coin_properties.png" alt="Spinning gold coin"/>
<p>For our enemy, it's a bit longer, and (just for the exercise) we are gonna do things a bit
differently this time by using a me.Sprite as a base object and add a physic body to it
"manually" :</p>
<pre><code>export class EnemyEntity extends me.Sprite {
/**
*
* @param x
* @param y
* @param settings
*/
constructor(x, y, settings) {
// save the area size as defined in Tiled
let width = settings.width;
// define this here instead of tiled
settings.image = "wheelie_right";
// adjust the size setting information to match the sprite size
// so that the entity object is created with the right size
settings.framewidth = settings.width = 64;
settings.frameheight = settings.height = 64;
// call the parent constructor
super(x, y , settings);
// add a physic body
this.body = new me.Body(this);
// add a default collision shape
this.body.addShape(new me.Rect(0, 0, this.width, this.height));
// configure max speed and friction
this.body.setMaxVelocity(4, 6);
this.body.setFriction(0.4, 0);
// enable physic collision (off by default for basic me.Renderable)
this.isKinematic = false;
// set start/end position based on the initial area size
x = this.pos.x;
this.startX = x;
this.pos.x = this.endX = x + width - this.width;
//this.pos.x = x + width - this.width;
// to remember which side we were walking
this.walkLeft = false;
// make it "alive"
this.alive = true;
}
// manage the enemy movement
update(dt) {
if (this.alive)
{
if (this.walkLeft === true) {
if (this.pos.x <= this.startX) {
// if reach start position
this.walkLeft = false;
this.flipX(false);
} else {
this.body.force.x = -this.body.maxVel.x;
}
}
if (this.walkLeft === false) {
if (this.pos.x >= this.endX) {
// if reach the end position
this.walkLeft = true;
this.flipX(true);
} else {
this.body.force.x = this.body.maxVel.x;
}
}
}
// return true if we moved or if the renderable was updated
return (super.update(dt) || this.body.vel.x !== 0 || this.body.vel.y !== 0);
}
/**
* colision handler
* (called when colliding with other objects)
*/
onCollision(response, other) {
if (response.b.body.collisionType !== me.collision.types.WORLD_SHAPE) {
// res.y >0 means touched by something on the bottom
// which mean at top position for this one
if (this.alive && (response.overlapV.y > 0) && response.a.body.falling) {
this.flicker(750, () => {
me.game.world.removeChild(this);
});
}
return false;
}
// Make all other objects solid
return true;
}
}
entities.EnemyEntity = EnemyEntity;
</code></pre>
<p>As you can see here, I specified the <b>settings.image</b> and <b>settings.framewidth</b>
properties in the constructor directly, meaning that in Tiled, I won't have to add these
properties to my Object (Once again, it's up to you to decide how to use it).</p>
<p>Also, I am using the <b>width</b> property given by Tiled to specify a path on which this enemy
will run. Finally, in the onCollision method, I make the enemy flicker if something is jumping
on top of it.</p>
<p>Note. This me.Sprite extends me.Renderable class, so you can use the <b>this.flicker(750)</b>
method directly.</p>
<p>Then again, we add these new objects in the Object Pool</p>
<pre><code>// register our object entities in the object pool
me.pool.register("mainPlayer", PlayerEntity);
me.pool.register("CoinEntity", CoinEntity);
me.pool.register("EnemyEntity", EnemyEntity);
</code></pre>
<br/>
<p>And we are ready to complete our level in Tiled. Create a new object layer, and use the Insert
Object tool to add coins and enemies where you want. Right-click on each object and make sure to
set their name to either CoinEntity or EnemyEntity.</p>
<img src="media/tutorial_tiled_step5.png" alt="Step 5"/>
<pre><code>/**
* update the player pos
*/
update(dt) {
if (me.input.isKeyPressed('left')) {
// flip the sprite on horizontal axis
this.renderable.flipX(true);
// update the default force
this.body.force.x = -this.body.maxVel.x;
// change to the walking animation
if (!this.renderable.isCurrentAnimation("walk")) {
this.renderable.setCurrentAnimation("walk");
}
} else if (me.input.isKeyPressed('right')) {
// unflip the sprite
this.renderable.flipX(false);
// update the entity velocity
this.body.force.x = this.body.maxVel.x;
// change to the walking animation
if (!this.renderable.isCurrentAnimation("walk")) {
this.renderable.setCurrentAnimation("walk");
}
} else {
// change to the standing animation
this.renderable.setCurrentAnimation("stand");
}
if (me.input.isKeyPressed('jump')) {
if (!this.body.jumping && !this.body.falling)
{
// set current vel to the maximum defined value
// gravity will then do the rest
this.body.force.y = -this.body.maxVel.y
}
} else {
this.body.force.y = 0;
}
return (super.update(dt) || this.body.vel.x !== 0 || this.body.vel.y !== 0);
}
</code></pre>
<p> Last but not least, as we added some platform in our level, let's modify the onCollision handler
to add a custom behavior for the "WORLD_SHAPE" type and simulate a "platform" element, as shown
below.</p>
<p>Do note that the particular collision shapes that we do want to act as "platforms" are here
identified by setting their type property to "platform" in Tiled (Feel free to use whatever you
need, as far as you use the same value on both ends).</p>
<pre><code>/**
* collision handler
*/
onCollision(response, other) {
switch (response.b.body.collisionType) {
case me.collision.types.WORLD_SHAPE:
// Simulate a platform object
if (other.type === "platform") {
if (this.body.falling &&
!me.input.isKeyPressed('down') &&
// Shortest overlap would move the player upward
(response.overlapV.y > 0) &&
// The velocity is reasonably fast enough to have penetrated to the overlap depth
(~~this.body.vel.y >= ~~response.overlapV.y)
) {
// Disable collision on the x axis
response.overlapV.x = 0;
// Repond to the platform (it is solid)
return true;
}
// Do not respond to the platform (pass through)
return false;
}
break;
case me.collision.types.ENEMY_OBJECT:
if ((response.overlapV.y>0) && this.body.falling) {
// bounce (force jump)
this.body.vel.y = -this.body.maxVel.y;
}
else {
// let's flicker in case we touched an enemy
this.renderable.flicker(750);
}
// Fall through
default:
// Do not respond to other objects (e.g. coins)
return false;
}
// Make the object solid
return true;
}
</code></pre>
<h3>Try it out</h3>
<p>And this is what you should get (note that I completed the level a little bit, adding platforms,
etc...):</p>
<a href="./tutorial_step5/index.html" target="_blank"><img src="media/tutorial_step5.png"
alt="Step 5 results"/></a>
<p>Try to collect your coins, avoid the enemy or jump on it!</p>
</div>
</div> <!-- end part 5 -->
<!-- PART 6 ========================================================================================= -->
<div>
<a id="part6" class="offset-anchor"></a>
<div class="subcontent">
<h2>Part 6: Adding some basic HUD information</h2>