forked from melonjs/melonJS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1514 lines (1236 loc) · 49.7 KB
/
index.html
File metadata and controls
1514 lines (1236 loc) · 49.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!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>
<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
}
/*]]>*/
</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">
<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.mapeditor.org/">Tiled Homepage</a></li>
<li><a href="http://www.tapjs.com/">TapJS Homepage</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><a href="http://www.mapeditor.org/">Tiled</a> version 0.7.x, installed
and running
</li>
<li>The melonJS <a href="http://www.melonjs.org/docs/index.html">documentation</a>
for more details
</li>
<li>
<a href="tutorial_template.zip">This template file</a>, containing what we will
use for the tutorial :
<ul>
<li>a copy of melonJS (0.9.2) (/lib)</li>
<li>a level tileset and a metatileset for collision
(/data/area01_tileset/)
</li>
<li>two background for parallax layers (/data/area01_parallax/)</li>
<li>some basic spritesheet (/data/sprite/)</li>
<li>some audio sfx and music (/data/audio/)</li>
<li>a title screen background (/data/GUI/)</li>
<li>a main.js skeleton</li>
<li>a default index.html</li>
</ul>
</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><b>Additional Credits :</b><br/>
- <a href=
"http://www.spicypixel.net/2008/01/10/gfxlib-fuzed-a-free-developer-graphic-library/">
SpicyPixel.NET</a> for the GfxLib-Fuzed assets<br/>
- <a href="http://www.nosoapradio.us/">noSoapRadio</a> for the in game music</p>
<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 wiki for further help</p>
<h2>Part 1: Creating a level using Tiled</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 adding a
"background_color" property to the map (Map/Map Properties), and just specify any
color (in CSS format) 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>Part 2: Loading our level</h2>
<p>First let's have a look at our main.js skeleton :</p>
<pre class="c2">
<code>
// game resources
var g_resources = [];
var jsApp = {
/* ---
Initialize the jsApp
--- */
onload: function() {
// init the video
if (!me.video.init('jsapp', 640, 480, false, 1.0)) {
alert("Sorry but your browser does not support html 5 canvas.");
return;
}
// initialize the "audio"
me.audio.init("mp3,ogg");
// set all resources to be loaded
me.loader.onload = this.loaded.bind(this);
// set all resources to be loaded
me.loader.preload(g_resources);
// load everything & display a loading screen
me.state.change(me.state.LOADING);
},
/* ---
callback when everything is loaded
--- */
loaded: function() {
// set the "Play/Ingame" Screen Object
me.state.set(me.state.PLAY, new PlayScreen());
// start the game
me.state.change(me.state.PLAY);
}
};
// jsApp
/* the in game stuff*/
var PlayScreen = me.ScreenObject.extend({
onResetEvent: function() {
// stuff to reset on state change
},
/* ---
action to perform when game is finished (state change)
--- */
onDestroyEvent: function() {
}
});
//bootstrap :)
window.onReady(function() {
jsApp.onload();
});
</code>
</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://www.melonjs.org/docs/symbols/me.ScreenObject.html"> <b>PlayScreen</b> object</a> that we will use to manage the game event (reset,
etc...).</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 here (for example) the <b>g_resources</b>
object :</p>
<ul>
<li>the tileset itself, an image</li>
<li>our map "area01", a <b>"tmx"</b> object</li>
</ul>
<pre class="c2">
<code>//game resources
var g_resources = [{
name: "area01_level_tiles",
type: "image",
src: "data/area01_tileset/area01_level_tiles.png"
}, {
name: "area01",
type: "tmx",
src: "data/area01.tmx"
}];
</code>
</pre>
<p>Be sure as well to correctly name the tileset resource name accordingly to the
filename, else the level loader will not be able to find the tileset and will
fail.</p>
<p>Finally, in the <b>onResetEvent()</b> function (which is called on a state
change), we ask the level director to display our previously preloaded level :</p>
<pre class="c2">
<code>/* the in game stuff*/
var 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() {
}
});
</code>
</pre>
<p><br/>
That's all! If you did everything correctly, and open you index.html, you should see
something like this:<br/>
(click on the image to see it running in your browser) <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 noticed, 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 create 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>Part 3: Add a main player</h2>
<p>Here we will create a new object by extending the default <a href="http://www.melonjs.org/docs/symbols/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="c2">
<code>//game resources
var g_resources = [{
name: "area01_level_tiles",
type: "image",
src: "data/area01_tileset/area01_level_tiles.png"
}, {
name: "area01",
type: "tmx",
src: "data/area01.tmx"
}, {
name: "gripe_run_right",
type: "image",
src: "data/sprite/gripe_run_right.png"
}];
</code>
</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 gameObj.js)</p>
<pre class="c2">
<code>/*-------------------
a player entity
-------------------------------- */
var PlayerEntity = me.ObjectEntity.extend({
/* -----
constructor
------ */
init: function(x, y, settings) {
// call the constructor
this.parent(x, y, settings);
// set the walking & jumping speed
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')) {
this.doWalk(true);
} else if (me.input.isKeyPressed('right')) {
this.doWalk(false);
} else {
this.vel.x = 0;
}
if (me.input.isKeyPressed('jump')) {
this.doJump();
}
// check & update player movement
this.updateMovement();
// update animation if necessary
if (this.vel.x!=0 || this.vel.y!=0) {
// update objet animation
this.parent(this);
return true;
}
return false;
}
});
</code>
</pre>
<p>I think the above code is quite easy to understand. Basically, we extend the
<a href="http://www.melonjs.org/docs/symbols/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://www.melonjs.org/docs/symbols/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>Note that the functions here above, like <b>doWalk()</b> and <b>doJump()</b>, are
actually <b>helper functions for platform games</b> that basically compute the new player
velocity based on the parameters defined by the <b>setVelocity()</b> function :
<pre class="c2">
<code>
/**
* helper function for platform games
* make the entity move left of right
* @param {Boolean} left will automatically flip horizontally the entity sprite
*/
doWalk : function(left) {
this.flipX(left);
this.vel.x += (left) ? -this.accel.x * me.timer.tick : this.accel.x * me.timer.tick;
},
</code>
</pre>
If you do plan to develop any other type of games (or if have more complex needs),
I do <b>not</b> recommend using these function, but to rather directly modify the entity velocity
based on your requirements.
</p>
<p>Then, we have to modify our "main" to actually declare our new Object in the
<a href="http://www.melonjs.org/docs/symbols/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="c2">
<code>
/* ---
callback when everything is loaded
--- */
loaded: function ()
{
// set the "Play/Ingame" Screen Object
me.state.set(me.state.PLAY, new PlayScreen());
// add our player entity in the entity pool
me.entityPool.add("mainPlayer", 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);
}
</code>
</pre>
<br/>
<p>And now we can add our entity into the level! Go back to Tiled, add an new Object
Layer, and finally a new Entity.<br/>
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
:<br/>
- <b>image</b> with the <b>gripe_run_right</b> value (name of our resource<br/>
- <b>spritewidth</b> with the value <b>64</b> which is the size of a single sprite in
the spritesheet<br/>
- <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.<br/>
<br/>
These two parameters will be passed as parameters (<a href="http://www.melonjs.org/docs/symbols/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"/>
<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><img src="media/step3_collision_draw.png" alt=
"Drawing the collision layer"/>
<p><br/>
Save everything, and if you now re-open you 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="c2">
<code>me.debug.renderHitBox = true;
</code>
</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="c2">
<code>/* -----
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);
},
</code>
</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"/>
<p>(Note: When you change the vertical size of the hitbox, be sure to keep the bottom
of the hitboxes aligned.</p>
<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, let's remove in Tiled the "background_color" property (Map/Map properties)
that we added previously at the end of Part 1. 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/area01_parallax/area01_bkg0.png</b> for the first background
layer</p><img src="media/area01_bkg0.png" alt="Parallax background 1"/>
<p><b>/data/area01_parallax/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="c2">
<code>// game resources
var g_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"
}];
</code>
</pre>
<p>Open Tiled, and add two new Tile Layer. These layers <b>MUST contains the keyword
"parallax"</b> for the engine to recognize it as a parallax layers. Be sure as well
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 add the following
property<br/>
- <b>imagesrc</b> property with the <b>area01_bkg0</b> value for the first layer
(<b>parallax_layer1</b> in my example), and <b>area01_bkg1</b> value for the second
one (<b>parallax_layer2</b> in my example)<br/></p>
<p><img src="media/step4_layer_property.png" alt=
"Configuring parallax properties"/></p>
<p><br/>
"Et voila!". If you now open you 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>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 : <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="c2">
<code>// game resources
var g_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"
},
];
</code>
</pre>
<br/>
<p>The coin itself is pretty easy; we just extend the <a href="http://www.melonjs.org/docs/symbols/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="c2">
<code>/*----------------
a Coin entity
------------------------ */
var 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 destroyed (here collected)
onDestroyEvent: function() {
// do something when collected
}
});
</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 :<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="c2">
<code>/* --------------------------
an enemy Entity
------------------------ */
var 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.flicker(45);
}
},
// manage the enemy movement
update: function() {
// do nothing if not visible
if (!this.visible)
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;
}
this.doWalk(this.walkLeft);
} 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 objet animation
this.parent(this);
return true;
}
return false;
}
});
</code>
</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>Then again, we add these new objects in the entityPool</p>
<pre class="c2">
<code>
// add our object entities in the entity pool
me.entityPool.add("mainPlayer", PlayerEntity);
me.entityPool.add("CoinEntity", CoinEntity);
me.entityPool.add("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. <img src=
"media/tutorial_tiled_step5.png" alt="Step 5"/></p>
<p>Before testing, we also need to modify our player to heck for collision with other
entities. In order to do this, we add a call to the <a href="http://www.melonjs.org/docs/symbols/me.game.html#collide"> <b>me.game.collide(this)</b></a>
function in our mainPlayer code, see below :</p>
<pre class="c2">
<code>
/* -----
update the player pos
------ */
update: function() {
if (me.input.isKeyPressed('left')) {
this.doWalk(true);
} else if (me.input.isKeyPressed('right')) {
this.doWalk(false);
} else {
this.vel.x = 0;
}
if (me.input.isKeyPressed('jump')) {
this.doJump();
}
// 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
this.forceJump();
} else {
// let's flicker in case we touched an enemy
this.flicker(45);
}
}
}
// update animation if necessary
if (this.vel.x!=0 || this.vel.y!=0) {
// update objet animation
this.parent(this);
return true;
}
return false;
}
});
</code>
</pre>
<p><br/>
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>Part 6: Adding some basic HUD information</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="c2">
<code>// game resources
var g_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"
}];
</code>
</pre>
<br/>
<p>Let's then define a new Object, that will extend the <a href="http://www.melonjs.org/docs/symbols/me.HUD_Item.html">me.HUD_Item</a>,
in which we will draw the object value using our font.</p>
<pre class="c2">
<code>/*--------------
a score HUD Item
--------------------- */
var 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);
},
/* -----
draw our score
------ */
draw: function(context, x, y) {
this.font.draw(context, this.value, this.pos.x + x, this.pos.y + y);
}
});
</code>
</pre>
<br/>
<p>And display it when we start a new game :</p>
<pre class="c2">
<code>/* the in game stuff*/
var PlayScreen = me.ScreenObject.extend({
onResetEvent: function() {
// load a level