"HTML5 challenge classic" is the hero of the next layer-Open Source lecture (1) falling from the sky

Source: Internet
Author: User

It is a classic mobile phone game for heroes on the lower layer. It used to be famous on Nokia mobile phones. Today we will use HTML5 and lufylegend to implement it step by step.

I. Preparations

First, you need to download lufylegend as follows:

Http://lufylegend.googlecode.com/files/lufylegend-1.7.0.rar

Next you need to understand lufylegend. The API introduction is as follows:

Http://lufylegend.com/lufylegend/api

Next we will prepare several images:

Character pictures

Game background

Game Wall

Top nail

Some friends may have sprayed blood when they saw it, and they wanted to beat me with a strong heart. Because my character pictures are carried by the Three Kingdoms. In fact, there is no way to go down. I can't find the figure. I only need to use this handsome taxi soldier.

Next let's perform initialization. First we need several layers to put characters, backgrounds, buildings, obstacles, etc. So we first define several layer variables.

var backLayer,loadingLayer,mapLayer,stageLayer,buildingLayer,charaLayer,overLayer;

In addition, some miscellaneous variables have been annotated and should be understandable:

// Array used to load the image var imglist ={}; var imgdata = [{name: "Player", path :". /images/player.png "},{ name:" back ", path :". /images/gameback.png "},{ name:" Apron ", path :". /images/apron.png "},{ name:" nail ", path :". /images/nail.png "}]; // character variable VAR hero; var charainix = 100; var charainiy = 100; var ismirror = false;

Then initialize the game:

init(30,"mylegend",stageWidth,stageHeight,main);

Init is the initialization function in lufylegend. You can check the usage in the API. Here it is not too long-winded. Next let's look at the main function:

Function main () {// initialize the loadinglayer = new loadingsample1 (); addchild (loadinglayer); // load the image and display the progress bar lloadmanage. load (imgdata, function (Progress) {loadinglayer. setprogress (Progress) ;}, function (result) {imglist = result; removechild (loadinglayer); loadinglayer = NULL; // start game initialization gameinit ();});}

This main function is used to load images in the game. After loading, it calls gameinit. Imgdata can be found in the variables defined above. It is not difficult to see that it is an array containing the image path. When loaded, the images in the game can be added to the game one by one. The lloadmanage method can be viewed in the API, because even if I explain it, I can only copy the items in the API.

Next let's take a look at gameinit:

Function gameinit () {// initialization layer initlayer (); // Add the game character addchara (); // Add the game event addevent (); // Add the game background addgameback (); // Add the game bezel addapron (); // Add the top nail addnail ();}

The above code has been annotated, so it is not difficult to understand. (You should also understand it, because it is all about calling functions)

At this point, game Initialization is done.

2. Implementation of game background

Just now we have read about gameinit, And we have finished talking about the movements in it. Let's look at the functions called in it.

The first is the initlayer, which can be known as the initial layer after reading English. The specific code is as follows:

Function initlayer () {// Add backlayer = new lsprite (); addchild (backlayer); // Add maplayer = new lsprite (); backlayer. addchild (maplayer); // adds the obstacle layer stagelayer = new lsprite (); backlayer. addchild (stagelayer); // Add the building layer buildinglayer = new lsprite (); backlayer. addchild (buildinglayer); // Add charalayer = new lsprite (); backlayer. addchild (charalayer); // Add another layer overlayer = new lsprite (); backlayer. addchild (overlayer );}

First, I instantiate the layer variable that I just defined as lsprite. Friends who may know something about it know this thing (although I don't know about it). It is equivalent to a container where images can be placed, text, button, drawing ...... Anything that can be put is omnipotent. This is lsprite. Lsprite can be understood as a layer, because it can easily achieve hierarchical effect.

The engine is developed in the same way as the ActionScript syntax. Of course, if you do not understand this, you can go over the API again. The details are very detailed.

After adding layers, we start to add characters.

Look at the code in addchara:

Function addchara () {// create a character hero = new charactor (); // determine the character location hero. X = charainix; hero. y = charainiy; // Add it to the character layer charalayer. addchild (HERO );}

The code here will be discussed separately later.

The next step is to add the event. You can look at the Code:

Function addevent () {// Add the mouse event backlayer. addeventlistener (lmouseevent. mouse_down, ondown); backlayer. addeventlistener (lmouseevent. mouse_up, onup); // Add the onframe to call the backlayer. addeventlistener (Levent. enter_frame, onframe);} function ondown (event) {// retrieve the mouse coordinate var mousex = event. offsetx; // determines the direction of a person's movement. Click the right of the person to move the person to the right. Click the left of the person to move the person to the left. If (mousex> hero. X + 20) {// The role moves charamove ("right");} else if (mousex 

For how to use addeventlistener, you can look at the API, which is different from the original addeventlistener usage in Js. Additionally, lmouseevent. mouse_down is a mouse click event, and lmouseevent. mouse_up is a mouse bullet event. Levent. enter_frame is a timeline event. Because our interface is constantly refreshed, we call the function corresponding to this event every time we refresh it.

The next three functions are full of painting backgrounds. addnail is the nail on the top, addapron is the wall on both sides of the game, and addgameback is the background image. The Code is as follows:

Function addgameback () {// The background block is displayed cyclically to tile the background for (VAR I = 0; I <4; I ++) {for (VAR J = 0; j <4; j ++) {var backbitmapdata = new lbitmapdata (imglist ["back"], 0, 0, 130,130); var backbitmap = new lbitmap (backbitmapdata ); // move the background block backbitmap after each painting. X = J * 130; backbitmap. y = I * 130; maplayer. addchild (backbitmap) ;}} function addapron () {// The cyclic display block is used to create two bezel for (VAR I = 0; I <15; I ++) {for (var j = 0; j <2; j ++) {var apronbitmapdata = new lbitmapdata (imglist ["Apron"], 0, 0, 17 ); vaR apronbitmap = new lbitmap (apronbitmapdata); // you can move the bezel block to apronbitmap. X = J * 383; apronbitmap. y = I * 34 + 20; buildinglayer. addchild (apronbitmap) ;}} function addnail () {// display nails cyclically to facilitate the laying of nails for (VAR I = 0; I <30; I ++) {var nailbitmapdata = new lbitmapdata (imglist ["nail"],); var nailbitmap = new lbitmap (nailbitmapdata); // remove the nail after each painting. X = I * 14 + 5; nailbitmap. y = 0; buildinglayer. addchild (nailbitmap );}}

In addgameback, we can see two classes: lbitmap and lbitmapdata. They are used for texture, lbitmapdata is used for image data, and lbitmap is used to plot data in lbitmapdata. For usage, see the API. Since our background image is small, I have to use either tile or stretch to fill the canvas. When I consider tiled or stretched, I think tiled can better handle the effect, and the image will not look good after stretching. So I tried to tile. I didn't expect that lufylegend was not tiled, and I couldn't write it myself.

I calculated that I had to fill the canvas. We had to draw four times horizontally and four times vertically.

Check the Code:

For (VAR I = 0; I <4; I ++) {for (VAR J = 0; j <4; j ++) {var backbitmapdata = new lbitmapdata (imglist ["back"], 130,130,); var backbitmap = new lbitmap (backbitmapdata); // move the background block backbitmap after each painting. X = J * 130; backbitmap. y = I * 130; maplayer. addchild (backbitmap );}}

I made a loop to set up a loop, so that each piece of it will be moved to the next position and then continue to be paved, so that the background can be paved.

The method for adding nails and walls is similar.

Run the Code with the following results:

Iii. Hero fall)

The name of this section is a bit strange. Of course, the strange thing is the English hero fall. In fact, this hero fall comes from the latest movie 007 skyscreen killer. Its English language is sky fall, so I also use it to play two or three more characters. Of course, I am not talking to you about movies, or how to write more characters. The main objective is to develop games. Ha!

I just spoke nonsense and now I am back in the game.

First, create a character class charactor. The Code is as follows:

/*** Charactor character class */function charactor () {base (this, lsprite, []); var self = This; // initialize the character mode to "stand" self. mode = "stand"; // splits the image into a two-dimensional array filled with coordinates var list = lglobal. dividecoordinate (192,256,); var DATA = new lbitmapdata (imglist ["Player"],); // Add the animation class self. anime = new lanimation (self, Data, list); // adjust the animation self. anime. setaction (, 1, false); // adjust the animation Frequency Variable self. step = 2; self. stepindex = 0 ;}

First, some friends may not understand it. Is base a God horse? It's the inheritance function in lufylegend. The parameters are: the class to be inherited, the base class (the inherited class), and passed to the parameter of the inherited class. Of course, the API is also introduced. If you want to know more, you can check it out. Next, we will jump to the self. Mode line. This mode plays a major role in the game, including determining whether to encounter obstacles and the direction of tasks. Next let's take a look at lglobal. dividecoordinate is used to cut coordinates. It can be used to break down an image into a two-dimensional array. This can be used to facilitate animation processing. You can refer to the API for more information.

After the construction, the variable hero can be instantiated in the addchara function. And add it to charalayer.

The lanimation class is an animation playing class. It can be used with lglobal. dividecoordinate for example:

init(100,"legend",800,450,main); var imgData = [ {name:"player",path:"player.png"} ]; var imglist; var backLayer,hero; function main(){     LLoadManage.load(imgData,null,gameInit); } function gameInit(result){    imglist = result;     backLayer = new LSprite();     addChild(backLayer);     var list = LGlobal.divideCoordinate(256,256,4,4);     var data = new LBitmapData(imglist["player"],0,0,64,64);     hero = new LAnimation(backLayer,data,list);     backLayer.addEventListener(LEvent.ENTER_FRAME,onframe); } function onframe(){     hero.onframe(); }

Lanimation:

Lanimation class lanimation (layer, Data, list)

■ Function: to play a simple animation, the principle is to display a large image one by one based on the coordinates saved in a two-dimensional array with coordinates. ■ Parameter: layer: lsprite display Layer
Data: lbitmapdata object
List: a two-dimensional array containing coordinates

Among the above three parameters, layer is an lsprite object, and data is an lbitmapdata object, which is easy to understand. The third parameter list is a two-dimensional array. Its format is as follows:

[  [{x:0,y:0},{x:0,y:0},{x:0,y:0}],  [{x:0,y:0},{x:0,y:0},{x:0,y:0}],  [{x:0,y:0},{x:0,y:0},{x:0,y:0}]  ]  

The setaction function of the lanimation object, which has four parameters:

Lanimation. setaction (rowindex, colindex, mode, ismirror) parameter: rowindex: Specifies the row number of the playback animation. colindex: Specifies the column number of the playback animation. Mode: (,-1) indicates (Forward playback, static, reverse playback) ismirror: Boolean. When set to true, the image is displayed as an image after horizontal flip.

For more information, see the API.

Add the run in charactor, and then add the animation to the run. In this way, the character can be moved.

Let's take a look at the run method:

Charactor. prototype. run = function () {var self = This; // keep the characters under self. Y + = fallspeed; // reduce the animation switching frequency if (self. stepindex ++> self. step) {self. stepindex = 0; self. anime. onframe ();} // determines the character mode to move the IF (self. mode = "Left") {// processing when moving to the left // determining whether the character has reached the leftmost canvas edge if (self. x> 10) {self. x-= herospeed;} else if (self. mode = "right") {// processing when moving to the right // determining whether the character has reached the rightmost canvas edge if (self. x <lstage. width-self. getwidth ()-20) {self. X + = herospeed;} else if (self. mode = "stand") {return ;}}

Then define the variable to control the descent speed and walking speed:

var heroSpeed = 10;var fallSpeed = 10;

It is not difficult to understand it with comments. First, our hero will continue to decline, so he will continue to add his Y coordinates. Next we will play the character animation, and the Code for playing the character animation is worth looking:

if(self.stepindex++ > self.step){self.stepindex = 0;self.anime.onframe();}

What does that mean? Because this run method is called every time the interface is refreshed, the refresh frequency is too high, and our animation speed is determined based on this frequency, how fast the animation of this character is so fast. Therefore, if you want to play a character animation every MS, you must set two variables: one is the refresh count variable and the other is the limitation variable. Variable Limit = frequency limit: refresh frequency. The initial value of the refresh count variable is 0. Let the refresh count variable add one after each refresh, and then determine whether it is greater than the variable. If so, set the refresh count variable to 0 and play a frame. In this way, the animation frequency can be limited.

Next, we will judge the walking direction of a person based on the mode and whether the person is walking. Check the code again;

If (self. mode = "Left") {// processing when moving to the left // determining whether the character has reached the leftmost canvas edge if (self. x> 10) {self. x-= herospeed;} else if (self. mode = "right") {// processing when moving to the right // determining whether the character has reached the rightmost canvas edge if (self. x <lstage. width-self. getwidth ()-20) {self. X + = herospeed;} else if (self. mode = "stand") {return ;}

When mode is left, the character shifts to the left, and the X coordinate is reduced. When mode is right, the character shifts to the right, and the X coordinate is added. When mode is right, the characters do not move.

But where can I change the mode? This also traces back to the function called in addevent.

Let's take a look at the functions called in addevent:

Function ondown (event) {// retrieve the mouse coordinate var mousex = event. offsetx; // determines the direction of a person's movement. Click the right of the person to move the person to the right. Click the left of the person to move the person to the left. If (mousex> hero. X + 20) {// The role moves charamove ("right");} else if (mousex 

When you press the mouse, we call the ondown function in addevent. Next let's look at the ondown function:

Function ondown (event) {// retrieve the mouse coordinate var mousex = event. offsetx; // determines the direction of a person's movement. Click the right of the person to move the person to the right. Click the left of the person to move the person to the left. If (mousex> hero. X + 20) {// The role moves charamove ("right");} else if (mousex 

First, we take out the mouse coordinates, and then determine the direction of the character, that is, the value of the X coordinate. If the mouse X coordinate is large, it is on the right side. Call charamove and assign the right parameter to the parameter. If the X coordinate of the character is large, it is on the left side. Then call charamove and assign the left parameter to the parameter; if it is not too small, you can stand in the same place.

Look at the code in charamove:

Function charamove (Direction) {Switch (Direction) {Case "right": // change the character mode "right" to convert it to hero. mode = "right" Hero. anime. setaction (, 1, true); // ismirror = true; break; Case "Left": // change the character mode to "Left ", convert it to hero. mode = "Left" Hero. anime. setaction (, 1, false); // change the direction variable ismirror = false; break ;}}

After entering this code, you can determine what the parameter is. When right is used, you can set the right mode of the character and change the character style. When left is set, the mode of the character is set to left and the character style is changed.

Call onup when you release the mouse, as shown below:

Function onup () {// loosen the mouse and change the shape of hero. mode = "stand"; // change the direction and appearance of the current station, hero. anime. setaction (0, 0, 1, ismirror );}

The code is very simple, that is, when you release the mouse, it changes the character's appearance and direction.

Next let's take a look at onframe:

Function onframe () {// use the run function in charactor to let the characters move hero. Run ();}

Since onframe is called every time the interface is refreshed, if the mode of the character is changed, the system will immediately respond.

Okay. Run the following command:

Press the mouse:

Test address: http://www.cnblogs.com/yorhom/archive/2013/04/06/3002850.html

Not bad, the hero is falling, and the hero will move if you press the mouse.

Now this hero is a zombie for us to play with, because there is no springboard he wants to see.

Next time, we will complete the stepping stone and blood reduction. I hope you will have more support.

Download this source code: http://files.cnblogs.com/yorhom/jump (1).rar

----------------------------------------------------------------

You are welcome to repost my article.

Reprinted Please note: transferred from yorhom's game box

Continue to follow my blog

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.