First Cocos2d-x Lua game

Source: Internet
Author: User

First Cocos2d-x Lua game
We wrote the first Cocos2d-x Lua program named HelloLua, learning other content from that project.
Create a project
We create a Cocos2d-x Lua project that can be implemented through the cocos command tool provided by the Cocos2d-x, but this method cannot be well integrated with the Cocos Code IDE integrated development tool, not easy to program writing and debugging. Since Cocos Code IDE tools are specifically designed for Cocos2d-x and Cocos2d-JS Lua development by Cocos2d-x, it is easy to use Cocos Code IDE tools to create Cocos2d-x Lua projects.
First, we need to configure the Lua framework in the Cocos Code IDE tool. Open the Cocos Code IDE tool and select Window> Preferences. In the displayed dialog box, select Cocos> Lua in Lua Frameworks on the right. .

Configuration of the Lua framework does not need to be performed every time. It is only configured at the beginning. However, when creating a project, the Cocos Code IDE tool creates a project file from the Lua framework directory.
Next, we can create a Lua Project. Choose File> New> Project from the menu, as shown in. The Project type selection dialog box is displayed.

Project Type Selection dialog box

Select the Cocos Lua Project and click Next to bring up the dialog box shown in. In the Project Name Project, enter the Project Name. Create Project in Workspace creates a Project in the Workspace directory. We need to select this Project, select the Create From Existing Resource project so that we can Create an Existing project. Now we do not need to select this project.
Click "Next" to go to the "Configure running environment" dialog box. In this dialog box, you can configure the project runtime information. The Orientation Project is the Orientation of the configuration simulator, where landscape is a horizontal screen display and portriat is a vertical screen display. Title in Desktop Runtime Settings is the Title of the simulator, and Desktop Windows initialize Size is the Size of the simulator. Add Native Codes is to Add local code to the project. In this case, we do not need to Add local code. Finally, click Finish to complete the creation. After the project is created, as shown in the following figure.
Create Project dialog box
Configure running environment dialog box
The project is successfully created and run in Cocos Code IDE.
After creating the project, we can test it. On the left-side project navigation panel, select the HelloLua project, right-click the project, and choose Run As → Cocos luainding from the context menu to Run the project we just created, shows the running result.

When running the project interface, we mainly compile the program code under the src directory. In this example, the Lua file is responsible for processing the main scenario interface logic. If you want to debug the program, you can set the breakpoint, as shown in. Click the position before the line number to set the breakpoint.

Set the breakpoint debugging and running process, right-click the menu, and choose Debug As → Cocos Luabinding. As shown in, the program runs to 31st rows and hangs, and enters the debugging view. In the debugging view, we can view the running stacks, variables, breakpoints, computing expressions, and single-step execution programs.



Running to breakpoint Suspension

Project file structure
The HelloLua project we created can run. Next we will introduce the file structure in the HelloLua project. We will use Cocos Code IDE To open the HelloLua project, as shown in the navigation panel on the left.

File structure in the HelloLua Project

In the navigation panel shown in, the res folder stores resource files. The src folder is the main program code main. lua and GameScene. lua, where main. lua is a program entry file that the Cocos2d-x binds at the underlying level and starts and runs it. GameScene. lua implements game scenarios.

Code explanation
There are two main files in the HelloLua project:

1. main. lua File
Main. lua is the program entry File Code as follows:

R

equire Cocos2d①-- ccloglocal cclog = function(...)②    print(string.format(...))③end-- for CCLuaEngine tracebackfunction __G__TRACKBACK__(msg)④    cclog(----------------------------------------)    cclog(LUA ERROR:  .. tostring(msg) .. )    cclog(debug.traceback())    cclog(----------------------------------------)    return msgendlocal function main()⑤    collectgarbage(collect)⑥    -- avoid memory leak    collectgarbage(setpause, 100)⑦    collectgarbage(setstepmul, 5000)⑧        cc.FileUtils:getInstance():addSearchPath(src)    cc.FileUtils:getInstance():addSearchPath(res)    cc.Director:getInstance():getOpenGLView():setDesignResolutionSize(480, 320, 0)        --create scene     local scene = require(GameScene)⑨    local gameScene = scene.create()⑩    gameScene:playBgMusic()        if cc.Director:getInstance():getRunningScene() then?        cc.Director:getInstance():replaceScene(gameScene)    else        cc.Director:getInstance():runWithScene(gameScene)    endendlocal status, msg = xpcall(main, __G__TRACKBACK__)?if not status then    error(msg)end


The first line of the above Code, require, is loading the Cocos2d module, and can avoid repeated loading. The Code in line ② declares the cclog function, which is used to output log information. Line ③ print (string. format (...) is the output function.
Line 4 of Code declares the _ g1_trackback _ (msg) function. When a program error occurs? Xpcall of rows, and stack information is output. The stack information of log output is as follows:
[LUA-print] stack traceback:[string .src/main.lua]:13: in function '__index'[string .GameScene.lua]:52: in function <[string .GameScene.lua]:49>[LUA-print] ----------------------------------------
The fifth line of code is the main () function, which is composed? The xpcall function of the row. The collectgarbage in the sixth line of code collectgarbage (collect) is a common interface function used to operate the Garbage Collector. Other definitions are as follows:
Collectgrabage (opt [, arg])
The opt parameter indicates the operation method, including the following:
Collect: execute a full garbage collection cycle. For details, see Row 6 of the Code.
Stop: stop the garbage collector.
Restart: restart the garbage collector.
Count: the number of memories used in the current Lua, in KB.
Step: Perform garbage collection in one step. The size attribute in the step size is specified by the arg parameter. If a collection cycle is completed, true is returned.
Setpause: Set the arg/100 value as the duration of the garbage collection pause. For details, see Line 7 of the Code.
Setstepmul: set the value of arg/100 as the step increase, that is, "new step" = "old step" * (arg/100). For details, see the second line of the Code.


The first line of the above Code is local scene = require (GameScene) to load the GameScene module. The returned value is a global variable of the table type. The code in the nth line is local gameScene = scene. create (). Use the static create () function to create the GameScene scenario.
Code number? Line cc. director: getInstance (): getRunningScene () is used to determine whether a scenario is running. If a scenario is running, cc is used. director: getInstance (): replaceScene (gameScene) Statement replaces the current scenario with the gameScene scenario. Otherwise, cc is used. director: getInstance (): runWithScene (gameScene) statement to run the gameScene scenario. Both the replaceScene and runWithScene function games will enter the gameScene scenario.
Code number? The xpcall function in line local status, msg = xpcall (main, _ g1_trackback _) is provided by Lua and used to call other functions and capture errors. The xpcall function is defined as follows:
Xpcall (f, err)
The f parameter indicates the function to be called, and the err parameter indicates the function called when a channel error is captured. The returned status is the error status and msg is the error message.
Actually number? Line Code local status, msg = xpcall (main, _ g1_trackback _) is the entry of the program. It calls the main () function, 3-19 shows the call sequence in the call stack.

Call Stack

2. GameScene. lua File
GameScene. lua is responsible for creating the main game scenario. The scenario shown in Figure 3-15 is implemented in GameScene. lua. The main code of GameScene. lua is as follows:
R
Equire Cocos2drequire Cocos2dConstants -- declare GameScene class local GameScene = class (GameScene, function () ① return cc. scene: create () end) -- Static creation function GameScene. create () ② local scene = GameScene. new () ③ scene: addChild (scene: createLayerFarm () ④ scene: addChild (scene: createLayerMenu () ⑤ return sceneend -- constructor GameScene: ctor () ⑥ self. visibleSize = cc. director: getInstance (): getVisibleSize () self. origin = c C. director: getInstance (): getVisibleOrigin () self. schedulerID = nilend -- playing background music function GameScene: playBgMusic () local bgMusicPath = cc. fileUtils: getInstance (): fullpathforfilename(background.pdf) cc. simpleAudioEngine: getInstance (): playMusic (bgMusicPath, true) local variable tpath = cc. fileUtils: getInstance (): fullPathForFilename(effect1.wav) cc. simpleAudioEngine: getInstance (): preloadEffect (effectPath) end- -Create the Dog genie function GameScene: creatDog () 7...... Local spriteDog = cc. Sprite: createWithSpriteFrame (frame0 )...... Return spriteDogend -- create farm Layer function GameScene: createLayerFarm () using local layerFarm = cc. Layer: create () creating...... Return layerFarmend -- create menu to create the menu Layer function GameScene: createLayerMenu () using local layerMenu = cc. Layer: create ()...... Return layerMenuendreturn GameScene

?
We created a GameScene scenario in GameScene. lua and added the farm layer and menu layer to the scenario. Line ① Code declares the GameScene scenario class, class (GameScene, function (){...}) A function is provided by the Cocos2d-x Lua engine and can create objects through Lua. The class function is defined as follows:
Class (classname, super)
The classname parameter is the function name, which is a string type, and super calls the parent class constructor.
The Code in line ② declares the GameScene. create () static function, which is called through the scene. create () Statement in main. lua. Line ③ code local scene = GameScene. new () is used to create a GameScene object. The new () function calls the GameScene: ctor () function of line 6. ctor () is the constructor used to initialize the GameScene scene object. The fourth line of code is to call the createLayerFarm () function of the GameScene scenario object to create the farm layer (see the first line of code ). The fifth line of code is to call the createLayerMenu () function of the GameScene scenario object to create the menu layer (see the first line of code ).
The function in line 7 of the Code is to create a Dog Genie and use the cc. Sprite: createWithSpriteFrame (frame0) statement to create the Sprite object. We will introduce it in detail later.
In the createfarm Layer function createLayerFarm (), the createLayerFarm line local layerFarm = cc. Layer: create () is the creation Layer object, which will be detailed later.

Number? The line code returns the GameScene variable, which is of the table type and returned when the local scene = require (GameScene) Statement is called in the main () function.

 

 

 

 

 

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.