forked from melonjs/tutorial-platformer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1480 lines (1185 loc) · 52.2 KB
/
index.html
File metadata and controls
1480 lines (1185 loc) · 52.2 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
<!DOCTYPE HTML>
<head>
<title>melonJS</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="style/style.css" title="style"/>
<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>
<script type="text/javascript" src="SyntaxHighlighter/shCore.js"></script>
<script type="text/javascript" src="SyntaxHighlighter/shBrushJScript.js"></script>
<link href="SyntaxHighlighter/shCore.css" rel="stylesheet" type="text/css" />
<link href="SyntaxHighlighter/shThemeDefault.css" rel="stylesheet" type="text/css" />
<style type="text/css">
/*<![CDATA[*/
pre.c2 {
font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace;
color: #000000;
background-color: #eee;
font-size: 12px;
border: 1px dashed #999999;
line-height: 14px;
padding: 5px;
overflow: auto;
width: 100%
}
p.c1 {
font-weight: bold;
padding: 0;
}
/*]]>*/
</style>
</head>
<body>
<div id="main">
<div id="header">
<div id="logo">
<div id="logo_text">
<!-- class="logo_colour", allows you to change the colour of the text -->
<h1><a href="http://www.melonjs.org">melon<span class=
"logo_colour">JS</span></a></h1>
<h2>A lightweight HTML5 game engine</h2>
</div>
</div>
</div>
<div id="site_content">
<a href="https://github.com/melonjs/melonjs"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_white_ffffff.png" alt="Fork me on GitHub"></a>
<div class="sidebar">
<p><img src="media/HTML5_Badge_128.png" alt="HTML5 badge"/></p>
<h3>Useful Links</h3>
<ul>
<li><a href="http://www.melonjs.org/">melonJS Homepage</a></li>
<li><a href="http://www.mapeditor.org/">Tiled Homepage</a></li>
<li><a href="http://melonjs.github.io/docs/">melonJS online documentation</a></li>
</ul>
</div>
<div id="content">
<!-- insert the page content here -->
<h1>A step by step game creation tutorial</h1>
<h2>Introduction:</h2>
<p class="c1">Prerequisites :</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/boilerplate/archive/master.zip">boilerplate</a>,
that we will use as default template project for our tutorial.
</li>
<li>
The tutorial <a href="tutorial_data.zip">data files</a>, to be uncompressed into the (here above) template data directory,
and which contains the following :</li>
<ul>
<li>a level tileset and a metatileset for collision </li>
<li>two backgrounds for parallax layers</li>
<li>some basic spritesheets </li>
<li>some audio sfx and music</li>
<li>a title screen background</li>
</ul>
<li>The melonJS <a href="http://www.melonjs.org/download.html"> library</a>,
to be copied under the /lib directory (be sure to download both the minified and plain version, as the latter might potentially be required for debugging purpose)
</li>
<li>The melonJS <a href="http://www.melonjs.org/docs/index.html">documentation</a>
for more details
</li>
</ul>
<p><b>Testing/debugging :</b><br/>
When using Chrome, and due to the "cross-origin request" security mechanism implemented,
you need to use the "--disable-web-security" parameter or better "--allow-file-access-from-files"
when launching the browser in order to test any local content, else the browser will complain
when trying to load a level map. <br/></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>
<h2><a id="part1">Part 1: Creating a level using Tiled</a></h2>
<p>melonJS supports only <i><b>uncompressed</b></i> tilemaps, so before continuing,
please check that your settings are correct (Tiled/Preferences). I recommend the
Base64 encoding, since it produces a smaller file, but it's really up to you.
<img src= "media/tiled_settings.png" alt="Tiled Settings"/></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>Then let's add both our tileset (using Map/New Tileset), and the "meta" tileset
that we will use for collision. Both have no spacing or margin, so be sure to let the
corresponding values to zero in tiled (note: melonJS support tilesets with margin and
space)</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 "data" folder. We are done
the first step!</p>
<h2><a id="part2">Part 2: Loading our level</a></h2>
<p>First let's have a look at our js/game.js skeleton :</p>
<pre class="brush: js">
/* game namespace */
var game = {
// Run on page load.
"onload" : function () {
// Initialize the video.
if (!me.video.init("screen", 640, 480, true, 'auto')) {
alert("Your browser does not support HTML5 canvas.");
return;
}
// add "#debug" to the URL to enable the debug Panel
if (document.location.hash === "#debug") {
window.onReady(function () {
me.plugin.register.defer(debugPanel, "debug");
});
}
// Initialize the audio.
me.audio.init("mp3,ogg");
// Set a callback to run when loading is complete.
me.loader.onload = this.loaded.bind(this);
// Load the resources.
me.loader.preload(game.resources);
// Initialize melonJS and display a loading screen.
me.state.change(me.state.LOADING);
},
// Run on game resources loaded.
"loaded" : function () {
me.state.set(me.state.MENU, new game.TitleScreen());
me.state.set(me.state.PLAY, new game.PlayScreen());
// Start the game.
me.state.change(me.state.PLAY);
}
};
</pre>
<p>This is very simple. Once the page is loaded, the <b>onload()</b> function is
called, the display and audio is initialized, and all game resources begin loading.
We also define a callback to be called when everything is ready to be used. Within
the callback, we define a new state that will be used for the in game stuff, together
with a <a href="http://melonjs.github.io/docs/me.ScreenObject.html"> <b>PlayScreen</b> object</a> that we will use to manage the game event (reset,
etc...).</p>
<p>The only change we will do in the default project template is the given video resolution for the `me.video.init()` function, as for the tutorial we will create a 640x480 canvas.
You will notice as well later that in the final version of the tutorial, I disabled video scaling by removing the 'auto' parameter, as my intention was to have it fitting my html template.</p>
<p>So in order to load our level, the next thing is to add the resources to be loaded
by adding the following information into <b>game.resources</b> (js/resources.js)
object :</p>
<ul>
<li>the tileset itself, an image</li>
<li>our map "area01", a <a href="https://github.com/bjorn/tiled/wiki/TMX-Map-Format">TMX</a> object</li>
</ul>
<pre class="brush: js">
//game resources
game.resources = [
/**
* Graphics.
*/
// our level tileset
{name: "area01_level_tiles", type:"image", src: "data/img/map/area01_level_tiles.png"},
/*
* Maps.
*/
{name: "area01", type: "tmx", src: "data/map/area01.tmx"}
];
</pre>
<p>Be sure to name the tileset resource name according to the
filename, or else the level loader will not be able to find the tileset and will fail.</p>
<p>Finally, let's open the js/screens/play.js file and in the <a href="http://melonjs.github.io/docs/me.ScreenObject.html#onResetEvent">onResetEvent()</a> function (which is called on a state
change), we ask the <a href="http://melonjs.github.io/docs/me.levelDirector.html">level director</a> to display our previously preloaded level :</p>
<pre class="brush: js">
/* the in game stuff*/
game.PlayScreen = me.ScreenObject.extend({
onResetEvent: function() {
// stuff to reset on state change
// load a level
me.levelDirector.loadLevel("area01");
},
/* ---
action to perform when game is finished (state change)
--- */
onDestroyEvent: function() {
}
});
</pre>
<p><br/>
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) :<br/>
</p>
<h3><a id="part2_try">Try it out</a></h3>
<p>(click on the image to see it running in your browser), you should see
something like this </br>
<a href=
"./tutorial_step2/index.html"><img
src="media/tutorial_step2.png" alt=
"Step 2 results"/></a><br/>
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>
<h2><a id="part3">Part 3: Add a main player</a></h2>
<p>Here we will create a new object by extending the default <a href="http://melonjs.github.io/docs/me.ObjectEntity.html"> me.ObjectEntity</a>, to create
our player. We will use the provided simple spritesheet <b>(gripe_run_right.png)</b>
to animate our character. It's of course possible to define different animation for
the same entity, but let's keep things simple first.</p><img src=
"media/gripe_run_right.png"
alt="Gripe run right"/>
<p>First, let's add our spritesheet in the list of the resources to be loaded, just
after our map :</p>
<pre class="brush: js">
//game resources
game.resources = [{
/**
* Graphics.
*/
// our level tileset
{name: "area01_level_tiles", type:"image", src: "data/img/map/area01_level_tiles.png"},
// the main player spritesheet
{name: "gripe_run_right", type:"image", src: "data/img/sprite/gripe_run_right.png"},
/*
* Maps.
*/
{name: "area01", type: "tmx", src: "data/map/area01.tmx"}
}];
</pre>
<p>Then it's time to create our entity:<br>
(Feel free to put this object either in our main.js or in a new file, in my example I use entities.js)</p>
<pre class="brush: js">
/*-------------------
a player entity
-------------------------------- */
game.PlayerEntity = me.ObjectEntity.extend({
/* -----
constructor
------ */
init: function(x, y, settings) {
// call the constructor
this.parent(x, y, settings);
// set the default horizontal & vertical speed (accel vector)
this.setVelocity(3, 15);
// set the display to follow our position on both axis
me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
},
/* -----
update the player pos
------ */
update: function() {
if (me.input.isKeyPressed('left')) {
// flip the sprite on horizontal axis
this.flipX(true);
// update the entity velocity
this.vel.x -= this.accel.x * me.timer.tick;
} else if (me.input.isKeyPressed('right')) {
// unflip the sprite
this.flipX(false);
// update the entity velocity
this.vel.x += this.accel.x * me.timer.tick;
} else {
this.vel.x = 0;
}
if (me.input.isKeyPressed('jump')) {
// make sure we are not already jumping or falling
if (!this.jumping && !this.falling) {
// set current vel to the maximum defined value
// gravity will then do the rest
this.vel.y = -this.maxVel.y * me.timer.tick;
// set the jumping flag
this.jumping = true;
}
}
// check & update player movement
this.updateMovement();
// update animation if necessary
if (this.vel.x!=0 || this.vel.y!=0) {
// update object animation
this.parent();
return true;
}
// else inform the engine we did not perform
// any update (e.g. position, animation)
return false;
}
});
</pre>
<p>I think the above code is quite easy to understand. Basically, we extend the
<a href="http://melonjs.github.io/docs/me.ObjectEntity.html"> ObjectEntity</a>, configure the default player speed, tweak the camera,
test if some keys are pressed and manage our player movement (by setting player speed, and then calling the <a href="http://melonjs.github.io/docs/me.ObjectEntity.html#updateMovement"> updateMovement</a> function). Also, you may notice that I'm
testing the final velocity (this.vel.x and this.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, we have to modify our "main" to actually declare our new Object in the
<a href="http://melonjs.github.io/docs/me.entityPool.html"> EntityPool</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 class="brush: js">
/* ---
callback when everything is loaded
--- */
"loaded" : function ()
{
// set the "Play/Ingame" Screen Object
me.state.set(me.state.PLAY, game.PlayScreen());
// add our player entity in the entity pool
me.entityPool.add("mainPlayer", game.PlayerEntity);
// enable the keyboard
me.input.bindKey(me.input.KEY.LEFT, "left");
me.input.bindKey(me.input.KEY.RIGHT, "right");
me.input.bindKey(me.input.KEY.X, "jump", true);
// start the game
me.state.change(me.state.PLAY);
}
</pre>
<br/>
<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 adding our Object into the entityPool), and add two properties to the Object:
<ul>
<li><b>image</b> : with the <b>gripe_run_right</b> value (name of our resource</li>
<li><b>spritewidth</b> : with the value <b>64</b> which is the size of a single sprite in the spritesheet</li>
<li><b>spriteheight</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>
These two parameters will be passed as parameters (<a href="http://melonjs.github.io/docs/me.ObjectSettings.html"><b>settings</b> object</a> here above
used by 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).<br/>
<br/>
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"/><br><br>
<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.
<img src="media/step3_object_position.png"alt="positioning an entity"/></p>
<h3><a id="define_collision_layer">Define the collision layer</a></h3>
<p>We are almost done! The last step is to define the collision layer, for this we
will use the other tileset we previously added into Tiled, and specify for each tile
a property corresponding to the tile type.</p><img src="media/step3_metatileset.png"
alt="Using the meta tileset"/>
<p>First, right click on the "Solid" tile (1st one), and add a <b>"type"</b> property
with <b>"solid"</b> as a value.</p><img src="media/step3_tile_solid.png" alt=
"Configuring the solid tile"/>
<p>Then, right click on the "Platform" tile (2nd one), and add a <b>"type"</b>
property with <b>"platform"</b> as a value.</p><img src=
"media/step3_tile_platform.png"
alt="Configuring the platform tile"/>
<p>That's it! Though we won't be using them for this tutorial, it is nice to know
that the others possible values are <b>"lslope"</b> for the left slope,
<b>"rslope"</b> for the right slope, <b>"ladder"</b> for ladder tiles and
<b>"breakable"</b> (you'll never guess) for breakable tiles. Also be careful when
defining these two fields, as the engine is exactly looking for these
labels, so if they are incorrect, it won't work.</p>
<p>Now add a new Tilelayer. This layer <b>MUST contains the keyword "collision"</b>
for the engine to recognize it as a collision layer.</p>
<p>Once the layer added, select it, and just "draw" you level collision map. At the
end it should look like this:</p>
<p><img src="media/step3_collision_draw.png" alt="Drawing the collision layer"/></p>
<h3><a id="part3_try">Try it out</a></h3>
<p>Save everything, and if you now re-open your index.html, you should see something like
this :<br/>
(click on the image to see it running in your browser) <a href=
"./tutorial_step3/index.html"><img
src="media/tutorial_step3.png" alt=
"Step 3 Results"/></a><br/></p>
<p>You will also notice that display is automatically following our player.</p>
<p>One last thing - when creating an object, a collision rectangle is automatically
created to manage collision between objects. For debugging purposes, you can use the
following debug settings in your main to enable it :</p>
<pre class="brush: js">
me.debug.renderHitBox = true;
</pre>
<p>If you reload the game, you will see this:</p><img src="media/step3_hitbox1.png"
alt="Enabling hit box"/>
<p>As you can see we have a lot of white space on the left and right of our
character, so let's adjust the collision rectangle to our sprite:</p>
<pre class="brush: js">
/* -----
constructor
------ */
init: function(x, y, settings) {
// call the constructor
this.parent(x, y, settings);
// set the walking & jumping speed
this.setVelocity(3, 15);
// adjust the bounding box
this.updateColRect(8, 48, -1, 0);
// set the display to follow our position on both axis
me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);
},
</pre>
<p>Here we add a horizontal 8 pixel offset, and set it's width to 48 pixels. We don't
change the height, so we specify -1.</p><img src="media/step3_hitbox2.png" alt=
"Tweaking the hit box"/>
<h2><a id="part4">Part 4: Add a scrolling background</a></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>/data/img/area01_bkg0.png</b> for the first background
layer</p><img src="media/area01_bkg0.png" alt="Parallax background 1"/>
<p><b>/data/img/area01_bkg1.png</b> for the second background
layer</p><img src="media/area01_bkg1.png" alt="Parallax background 2"/>
<p>Let's add them in the resource list:</p>
<pre class="brush: js">
// game resources
game.resources = [
/**
* Graphics.
*/
// our level tileset
{name: "area01_level_tiles", type:"image", src: "data/img/map/area01_level_tiles.png"},
// the main player spritesheet
{name: "gripe_run_right", type:"image", src: "data/img/sprite/gripe_run_right.png"},
// the parallax background
{name: "area01_bkg0", type:"image", src: "data/img/area01_bkg0.png"},
{name: "area01_bkg1", type:"image", src: "data/img/area01_bkg1.png"},
/*
* Maps.
*/
{name: "area01", type: "tmx", src: "data/map/area01.tmx"}
];
</pre>
<p>Open Tiled, and add two new <a href="http://melonjs.github.io/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 : <br/>
- Click the <b>browse</b> button and select the <b>area01_bkg0</b> image for the first layer
(<b>Parallax_layer1</b> on the picture), and <b>area01_bkg1</b> value for the second
one (<b>Parallax_layer2</b> also on the picture)<br/></p>
<p><img src="media/step4_Imagelayer_property.png" alt=
"Configuring Image Layer properties"/></p>
- And finally add a <a href="http://melonjs.github.io/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).
<br/></p>
<p>Note that default behavior for Image Layer is to be automatically <a href="http://melonjs.github.io/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><a id="part4_try">Try it out</a></h3>
<p>"Et voila!". If you now open your index.html, you should see:<br/>
<a href="./tutorial_step4/index.html"><img src="media/tutorial_step4.png" alt=
"Step 4 results"/></a><br/></p>
<p>Play around with your player, and enjoy the view :)</p>
<h2><a id="part5">Part 5: Adding some basic objects and enemies</a></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 : <img src=
"media/spinning_coin_gold.png"
alt="Spinning gold coin"/></p>
<p>And a basic enemy, using the <b>wheelie_right.png</b> spritesheet : <img src=
"media/wheelie_right.png"
alt="Wheelie right sprite"/></p>
<p>As always, add them to the resource list:</p>
<pre class="brush: js">
// game resources
game.resources = [
/**
* Graphics.
*/
// our level tileset
{name: "area01_level_tiles", type:"image", src: "data/img/map/area01_level_tiles.png"},
// the main player spritesheet
{name: "gripe_run_right", type:"image", src: "data/img/sprite/gripe_run_right.png"},
// the parallax background
{name: "area01_bkg0", type:"image", src: "data/img/area01_bkg0.png"},
{name: "area01_bkg1", type:"image", src: "data/img/area01_bkg1.png"},
// the spinning coin spritesheet
{name: "spinning_coin_gold", type:"image", src: "data/img/sprite/spinning_coin_gold.png"},
// our enemty entity
{name: "wheelie_right", type:"image", src: "data/img/sprite/wheelie_right.png"},
/*
* Maps.
*/
{name: "area01", type: "tmx", src: "data/map/area01.tmx"}
];
</pre>
<br/>
<p>The coin itself is pretty easy; we just extend the <a href="http://melonjs.github.io/docs/me.CollectableEntity.html"> me.CollectableEntity</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 class="brush: js">
/*----------------
a Coin entity
------------------------ */
game.CoinEntity = me.CollectableEntity.extend({
// extending the init function is not mandatory
// unless you need to add some extra initialization
init: function(x, y, settings) {
// call the parent constructor
this.parent(x, y, settings);
},
// this function is called by the engine, when
// an object is touched by something (here collected)
onCollision: function() {
// do something when collected
// make sure it cannot be collected "again"
this.collidable = false;
// remove it
me.game.remove(this);
}
});
</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 :<br>
<img src="media/coin_properties.png" alt="Spinning gold coin"/>
</p>
<br/>
<p>For our enemy, it's a bit longer :</p>
<pre class="brush: js">
/* --------------------------
an enemy Entity
------------------------ */
game.EnemyEntity = me.ObjectEntity.extend({
init: function(x, y, settings) {
// define this here instead of tiled
settings.image = "wheelie_right";
settings.spritewidth = 64;
// call the parent constructor
this.parent(x, y, settings);
this.startX = x;
this.endX = x + settings.width - settings.spritewidth;
// size of sprite
// make him start from the right
this.pos.x = x + settings.width - settings.spritewidth;
this.walkLeft = true;
// walking & jumping speed
this.setVelocity(4, 6);
// make it collidable
this.collidable = true;
// make it a enemy object
this.type = me.game.ENEMY_OBJECT;
},
// call by the engine when colliding with another object
// obj parameter corresponds to the other object (typically the player) touching this one
onCollision: function(res, obj) {
// res.y >0 means touched by something on the bottom
// which mean at top position for this one
if (this.alive && (res.y > 0) && obj.falling) {
this.renderable.flicker(45);
}
},
// manage the enemy movement
update: function() {
// do nothing if not in viewport
if (!this.inViewport)
return false;
if (this.alive) {
if (this.walkLeft && this.pos.x <= this.startX) {
this.walkLeft = false;
} else if (!this.walkLeft && this.pos.x >= this.endX) {
this.walkLeft = true;
}
// make it walk
this.flipX(this.walkLeft);
this.vel.x += (this.walkLeft) ? -this.accel.x * me.timer.tick : this.accel.x * me.timer.tick;
} else {
this.vel.x = 0;
}
// check and update movement
this.updateMovement();
// update animation if necessary
if (this.vel.x!=0 || this.vel.y!=0) {
// update object animation
this.parent();
return true;
}
return false;
}
});
</pre>
<p>As you can see here, I specified the <b>settings.image</b> and
<b>settings.spritewidth</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).<br/>
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 that an Object Entity drawable component (either a single sprite of animation) is
accessible through the Entity `renderable` property, which explains here why we do here the following : `this.renderable.flicker(45);`</p>
<p>Then again, we add these new objects in the entityPool</p>
<pre class="brush: js">
// add our object entities in the entity pool
me.entityPool.add("mainPlayer", game.PlayerEntity);
me.entityPool.add("CoinEntity", game.CoinEntity);
me.entityPool.add("EnemyEntity", game.EnemyEntity);
</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. <img src=
"media/tutorial_tiled_step5.png" alt="Step 5"/></p>
<p>Before testing, we also need to modify our player to check for collision with other
entities. In order to do this, we add a call to the <a href="http://melonjs.github.io/docs/me.game.html#collide"> <b>me.game.collide(this)</b></a>
function in our mainPlayer code, see below :</p>
<pre class="brush: js">
/* -----
update the player pos
------ */
update: function() {
if (me.input.isKeyPressed('left'))
{
// flip the sprite on horizontal axis
this.flipX(true);
// update the entity velocity
this.vel.x -= this.accel.x * me.timer.tick;
}
else if (me.input.isKeyPressed('right'))
{
// unflip the sprite
this.flipX(false);
// update the entity velocity
this.vel.x += this.accel.x * me.timer.tick;
}
else
{
this.vel.x = 0;
}
if (me.input.isKeyPressed('jump'))
{
if (!this.jumping && !this.falling)
{
// set current vel to the maximum defined value
// gravity will then do the rest
this.vel.y = -this.maxVel.y * me.timer.tick;
// set the jumping flag
this.jumping = true;
}
}
// check & update player movement
this.updateMovement();
// check for collision
var res = me.game.collide(this);
if (res) {
// if we collide with an enemy
if (res.obj.type == me.game.ENEMY_OBJECT) {
// check if we jumped on it
if ((res.y > 0) && ! this.jumping) {
// bounce (force jump)
this.falling = false;
this.vel.y = -this.maxVel.y * me.timer.tick;
// set the jumping flag
this.jumping = true;
} else {
// let's flicker in case we touched an enemy
this.renderable.flicker(45);
}
}
}
// update animation if necessary
if (this.vel.x!=0 || this.vel.y!=0) {
// update object animation
this.parent();
return true;
}
// else inform the engine we did not perform
// any update (e.g. position, animation)
return false;
}
});
</pre>
<h3><a id="part5_try">Try it out</a></h3>
<p>And this is what you should get (note that I completed the level a little bit, adding
platforms, etc...) :<br/>
<a href="./tutorial_step5/index.html"><img src="media/tutorial_step5.png" alt=
"Step 5 results"/></a><br/></p>
<p>Try to collect your coins, avoid the enemy or jump on it!</p>
<h2><a id="part6">Part 6: Adding some basic HUD information</a></h2>
<p>It's time now to display some score when we collect those coins, right?</p>
<p>We will use a bitmap font <b>(data/sprite/32x32_font.png)</b> to display our
score, as always we need to add it in our list of resources to be loaded :</p>
<pre class="brush: js">
// game resources
game.resources = [
// our level tileset
{
name: "area01_level_tiles",
type: "image",
src: "data/area01_tileset/area01_level_tiles.png"
},
// our level
{
name: "area01",
type: "tmx",
src: "data/area01.tmx"
},
// the main player spritesheet
{
name: "gripe_run_right",
type: "image",
src: "data/sprite/gripe_run_right.png"
},
// the parallax background
{
name: "area01_bkg0",
type: "image",
src: "data/area01_parallax/area01_bkg0.png"
}, {
name: "area01_bkg1",
type: "image",
src: "data/area01_parallax/area01_bkg1.png"
},
// the spinning coin spritesheet
{
name: "spinning_coin_gold",
type: "image",
src: "data/sprite/spinning_coin_gold.png"
},
// our enemty entity
{
name: "wheelie_right",
type: "image",
src: "data/sprite/wheelie_right.png"
},
// game font
{
name: "32x32_font",
type: "image",
src: "data/sprite/32x32_font.png"
}];
</pre>
<br/>
<p>Let's then define a new Object, that will extend the <a href="http://melonjs.github.io/docs/me.HUD_Item.html">me.HUD_Item</a>,
in which we will draw the object value using our font.</p>
<pre class="brush: js">
/*--------------
a score HUD Item
--------------------- */
game.ScoreObject = me.HUD_Item.extend({
init: function(x, y) {
// call the parent constructor
this.parent(x, y);
// create a font
this.font = new me.BitmapFont("32x32_font", 32);
this.font.set("right");
},
/* -----
draw our score
------ */
draw: function(context, x, y) {
this.font.draw(context, this.value, this.pos.x + x, this.pos.y + y);
}
});
</pre>
<br/>
<p>And display it when we start a new game :</p>
<pre class="brush: js">
/* the in game stuff*/
game.PlayScreen = me.ScreenObject.extend({
onResetEvent: function() {
// load a level
me.levelDirector.loadLevel("area01");
// add a default HUD to the game mngr
me.game.addHUD(0, 430, 640, 60);
// add a new HUD item
me.game.HUD.addItem("score", new game.ScoreObject(620, 10));
// make sure everything is in the right order
me.game.sort();
},
/* ---
action to perform when game is finished (state change)
--- */