The Hero

No game can exist without the hero. The hero will save the world and get the princess and beat up the bad guys. We will add hero too. He wont save the world yet, he wont do anything useful, but he will be ready for action:

The hero is red squary obejct. What, he doesnt look mighty enough for you? The red square is perfectly capable of saving the world and beating up the bad guys.

Go into prepareGame function and add these lines before calling buildMap function:

hSheet = new HeroSheet(0,0);
hero = new Object();
hero.sprNum = 0;
hero.sheet = hSheet;
hero.ts = 24;
hero.xtile = 2;
hero.ytile = 1;

Here we create new object, named "hero" so the object knows who gets into world-saving business later. The hero object will hold all the information about our character, how he moves, how he feels, what he eats. After hero has born, he is later added to screen, the hero is very much like improved tile, only he can eventually walk around and kill baddies.

The herosheet is bitmap similar to tilesheet where the graphics of our hero have been drawn. Currently we use 1 image only so the sprite to be shown from herosheet is 0.

New hero has properties xtile and ytile showing where will be his starting position. Those give us the tile our hero stands on at the birth moment. When he moves around, we will update the xtile/ytile properties and we will always know what tile is under the hero. For example, when xtile=2 and ytile=1 (like we wrote in code), that means hero is standing on the tile "t_1_2". When you look at the example movie, you see that hero stands on the tile 3 positions left and 2 positions down from the upper left corner of our game. All the tiles start counting from 0.

Variable ts marks the size of hero. Hero can be sometimes same size as the tiles, but he can also be smaller (making hero larger then tile is possible but quite difficult task and wont be covered). While we use squared hero in the example, not all heros are squares. Some of them may be tall and some may be wide, in that case separate the ts variable into width and height.

Now, in buildMap function, after loop to create tiles add this code:

hero.bmp = getImageFromSheet (hero, hero.sprNum);
hero.x = hero.xtile * ts;
hero.y = hero.ytile * ts;
hero.bmp.x = hero.x;
hero.bmp.y = hero.y;
myParent.addChild (hero.bmp);

We use same getImageFromSheet function to get correct bitmap image from the herosheet into hero object. We also find its coordinates on screen based on which tile he stands on (multiplied with the size of tiles) and we add the image of hero on screen. Unlike tiles, hero is not drawn directly on main screen-sized bitmap, as he needs to move around later and updating whole screen every time little hero moves is bad idea. Instead, we add the image of hero on top of tiles bitmap as separate bitmap.

You can download the source fla with all the code and movie set up here.

Next: Keys to Move.

Top