First Cocos2d-x LUA game

Source: Internet
Author: User

First Cocos2d-x LUA game

Our first cocos2d-x Lua program, named Hellolua, began to learn other things from the project.
Create a project
Our creation of the Cocos2d-x LUA project can be implemented cocos by the command tools provided by Cocos2d-x, but this approach is not well integrated with Cocos Code IDE integrated development tools and is not easy to program and debug. Because the Cocos Code IDE tool was developed specifically for COCOS2D-JS and cocos2d-x Lua development, the Cocos Code IDE tool makes it easy 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, select the menu window→preferences, pop Up the dialog box, select Cocos→lua in the LUA frameworks on the right <cocos2d-x Engine Catalog >.

Configuring the LUA Framework

The LUA framework configuration does not need to be done every time, but only in the initial configuration, but when the project is created, the Cocos Code IDE tool creates the project file from the LUA framework directory.
Next we can create a LUA project, select the menu File→new→project, as shown in the Popup Item Type selection dialog box.

Project Type selection dialog box



We selected Cocos Lua Project and then clicked the Next button to pop up the dialog box as shown. We enter the project name in Project name, the Create project in Workspace is created in the workspace directory, we need to select the project, create from Existing Resource item selection lets us create from an existing project, and now we don't need to select it.
Select Finish click the Next button to go to the Configure Run Environment dialog box where we can configure the project run-time information. The orientation project is the orientation of the configuration emulator, where landscape is a horizontal screen display, and the portriat is a vertical screen. The title in the desktop Runtime settings is the header of the set emulator, and the desktop Windows initialize size is the setting emulator. Add Native codes is to set up adding local code to the project, and in the original we do not need to add local code. Finally click the Finish button to complete the creation and create the project, as shown in the following figure.

New Project Dialog box

Configure the Run Environment dialog box

Create a project Success interface

Running in the Cocos Code IDE
After creating the project we can test, in the left of the Project navigation panel selected in the Hellolua project, the right-click menu select Run As→cocos luainding run the project we just created, run the result as shown.

Run the Engineering interface

Our main programming code is in the SRC directory, in this case the LUA file is responsible for handling the main scene interface logic. If we want to debug the program, we can set breakpoints, as shown in, click the position before the line number, set the breakpoint.

Set breakpoints

Debug the Run process, select the Debug As→cocos luabinding menu in the right-click menu. As shown, the program runs to line 31st pending and into the debug view, in the debug view we can see the stack, variables, breakpoints, calculation expressions, and stepping programs that the program runs.


Run to Breakpoint pending



Project file Structure
The Hellolua project we created has been able to run, let's look at the file structure in the Hellolua project, we use the Cocos Code IDE to open the Hellolua project, as shown in the navigation panel on the left.

Document structure in the Hellolua project



In the navigation panel shown, the Res folder holds the resource file, the SRC folder is the main program code Main.lua and Gamescene.lua, where Main.lua is the program portal file, Cocos2d-x binds the file at the bottom and starts and runs it. The game scene is implemented in Gamescene.lua.

Code explanation
There are two documents in the Hellolua project. Below we explain in detail their internal code:

1. Main.lua file
Main.lua is the program entry file code as follows:

R

[HTML]View Plaincopy
  1. Equire "Cocos2d" ①
  2. --Cclog
  3. Local Cclog = function (...) ②
  4. Print (String.Format (...)) ③
  5. End
  6. --For Ccluaengine Traceback
  7. function __g__trackback__ (msg) ④
  8. Cclog ("----------------------------------------")
  9. Cclog ("LUA ERROR:"). ToString (msg): "\ n")
  10. Cclog (Debug.traceback ())
  11. Cclog ("----------------------------------------")
  12. Return msg
  13. End
  14. Local function main () ⑤
  15. CollectGarbage ("collect") ⑥
  16. --Avoid memory leak
  17. CollectGarbage ("Setpause", 100) ⑦
  18. CollectGarbage ("Setstepmul", 5000) ⑧
  19. Cc. Fileutils:getinstance (): Addsearchpath ("src")
  20. Cc. Fileutils:getinstance (): Addsearchpath ("res")
  21. Cc. Director:getinstance (): Getopenglview (): Setdesignresolutionsize (480, 320, 0)
  22. --create scene
  23. Local scene = require ("Gamescene") ⑨
  24. Local Gamescene = scene.create () ⑩
  25. Gamescene:playbgmusic ()
  26. If CC. Director:getinstance (): Getrunningscene () then?
  27. Cc. Director:getinstance (): Replacescene (Gamescene)
  28. Else
  29. Cc. Director:getinstance (): Runwithscene (Gamescene)
  30. End
  31. End
  32. Local status, msg = Xpcall (main, __g__trackback__)?
  33. If not status Then
  34. Error (MSG)
  35. End



The above code, ① line require, is loading the cocos2d module and can avoid repeated loading. The ② Line code declares the Cclog function, which functions as output log information. Line ③ Code print (String.Format (...)) is the output function.
The ④ Line code is a declaration __g__trackback__ (msg) function, called by the Xpcall of the line when the program goes wrong, and outputs the stack information. The following is the stack information for the log output:

[HTML]View Plaincopy
    1. [Lua-print] Stack traceback:
    2. [string]. \src/main.lua "]:13:in function ' __index '
    3. [string]. \gamescene.lua "]:52:in function <[string". \gamescene.lua "]:49>
    4. [Lua-print]----------------------------------------

The ⑤ line code is the main () function, which is called by the Xpcall function of the first row. The CollectGarbage in line ⑥ code collectgarbage ("collect") is the common interface function of the garbage collector, which is used to manipulate the garbage collector, and the other definitions are as follows:
Collectgrabage (opt [, Arg])
The OPT parameter is an operation method flag, and the flags include the following:
Collect: Perform a full garbage collection cycle, see Code line ⑥.
Stop: Stop the garbage collector.
Restart: Restart the garbage collector.
Count: Returns the amount of memory used in the current LUA, in kilobytes.
Step: Stepping through a garbage collection, the Size property in step size is specified by the parameter arg and returns True if a collection cycle is completed.
Setpause: Set the value of arg/100 as the time of the garbage collection pause, see Code section ⑦ line.
Setstepmul: Set the value of arg/100 as the increment of step, that is, "new step" = "Old Step" * (arg/100), see Code section ⑧ line.


The above code, line ⑨, local scene = require ("Gamescene") loads the Gamescene module, and the return value is the table type global variable. The ⑩ line code local Gamescene = Scene.create () Creates a gamescene scene from the static Create () function.
Code line CC. Director:getinstance (): Getrunningscene () is to determine if there is a scene running if there is a scene running through CC. Director:getinstance (): Replacescene (gamescene) statement replaces the current scene with a gamescene scene, otherwise through CC. Director:getinstance (): Runwithscene (gamescene) statement runs the gamescene scene, Either the Replacescene or the Runwithscene function game will be entered into the gamescene scene.
The code of the local status, MSG = Xpcall (main, __g__trackback__) in the Xpcall function is provided by LUA, used to invoke other functions, and can catch the error, the Xpcall function is defined as follows:
Xpcall (f, Err)
Where the f parameter is the function to invoke, err is the function that is called when the path error is caught. The return value status is the error status and MSG is the error message.
In fact, the first line of code local status, MSG = Xpcall (main, __g__trackback__) is the entry of the program. It calls the main () function, 3-19, as shown in the call stack, and is able to see the order in which they are called.

Call stack



2. Gamescene.lua file
Gamescene.lua is responsible for creating the main game scene, we see the scene shown in Figure 3-15 is implemented in the Gamescene.lua, Gamescene.lua the main code is as follows:
R

[HTML]View Plaincopy
  1. Equire "Cocos2d"
  2. Require "cocos2dconstants"
  3. --Declaring the Gamescene class
  4. Local Gamescene = Class ("Gamescene", function () ①
  5. return CC. Scene:create ()
  6. End
  7. --Create a function statically
  8. function Gamescene.create () ②
  9. Local scene = gamescene.new () ③
  10. Scene:addchild (Scene:createlayerfarm ()) ④
  11. Scene:addchild (Scene:createlayermenu ()) ⑤
  12. Return scene
  13. End
  14. --Constructor function
  15. function Gamescene:ctor () ⑥
  16. self.visiblesize = cc. Director:getinstance (): Getvisiblesize ()
  17. Self.origin = cc. Director:getinstance (): Getvisibleorigin ()
  18. Self.schedulerid = Nil
  19. End
  20. --Play background music
  21. function Gamescene:playbgmusic ()
  22. Local Bgmusicpath = cc. Fileutils:getinstance (): Fullpathforfilename ("Background.mp3")
  23. Cc. Simpleaudioengine:getinstance ():p laymusic (Bgmusicpath, True)
  24. Local Effectpath = cc. Fileutils:getinstance (): Fullpathforfilename ("Effect1.wav")
  25. Cc. Simpleaudioengine:getinstance ():p reloadeffect (Effectpath)
  26. End
  27. --Create a dog wizard
  28. function Gamescene:creatdog () ⑦
  29. ... ...
  30. Local Spritedog = cc. Sprite:createwithspriteframe (FRAME0)
  31. ... ...
  32. Return Spritedog
  33. End
  34. --Create farm to build farms layer
  35. function Gamescene:createlayerfarm () ⑧
  36. Local layerfarm = cc. Layer:create () ⑨
  37. ... ...
  38. Return Layerfarm
  39. End
  40. --Create menu creates the menus layer
  41. function Gamescene:createlayermenu () ⑩
  42. Local Layermenu = cc. Layer:create ()
  43. ... ...
  44. Return Layermenu
  45. End
  46. Return Gamescene


?
We created the gamescene scene in Gamescene.lua and added a farm layer and a menu layer to the scene. The ① Line code is the declaration of the Gamescene scene class ("Gamescene", function () {...}) Functions are provided by the Cocos2d-x LUA engine and can be created by Lua. The class function is defined as follows:
Class (classname, Super)
Where parameter classname is the function name, it is a string type, and super is called the parent class constructor.
The ② Line code declares the gamescene.create () static function, which is called through the scene.create () statement in Main.lua. The ③ line code local scene = Gamescene.new () is the creation of the Gamescene creation object, the new () function calls the Gamescene:ctor () function of the ⑥ row, the ctor () is the constructor, Used to initialize the Gamescene scene object. The ④ line of code is to invoke the Createlayerfarm () function of the Gamescene scene object to create the farm layer (see Code ⑧ Line). The ⑤ line code is to invoke the Createlayermenu () function of the Gamescene scene object to create a menu layer (see Code ⑩ Line).
The Code ⑦ Line function is to create the dog Sprite, using CC. The Sprite:createwithspriteframe (FRAME0) statement creates the Sprite object, which we'll cover in more detail later.
The ⑨ line in the Create Farm layer function Createlayerfarm () is local layerfarm = cc. Layer:create () is the creation layer object, which we'll cover in more detail later.

The first line of code returns the Gamescene variable, which is the table type, which is returned when the local scene = require ("Gamescene") statement is called in the main () function.

First Cocos2d-x LUA game

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.