HelloLua Cocos2d-x-Lua sample project

Source: Internet
Author: User

HelloLua Cocos2d-x-Lua sample project

HelloLua Cocos2d-x-Lua sample project


This blog introduces the Lua instance project in the Cocos2d-x, which is the farm presented by running the initial project created using the Cocos2d-x. Here I named it HelloLua. This blog will detail in the code parsing the Lua project instance created by Cocos2d-x 3.1.1, the use of Some APIs.

Note: This example project is created on Mac

First we create a Cocos2d-x Lua project, and in the command, knock in a command similar to the following

Cocos new HelloLua-p com. wwj. hellolua-l lua-d ~ /Cocos2dxProj

In this way, a Lua project named HelloLua is created under the Cocos2dxProj directory.

Open the proj. ios_mac directory under our runtime-src directory, and double-click to use Xcode to open our project:

Using Xcode to compile and run our Lua project presents an example game with the following effects:


After reading this, let's take a look at the project file structure in XCode, such:

The above Circles include main. cpp, AppDelegate. h, AppDelegate. cpp, main. lua, and hello2.lua.

Let's take a look at it one by one:

First, let's take a look at the main. cpp file. This file is the entry file of our program, starting from here when the program runs.

"Main. cpp

#include "AppDelegate.h"#include "cocos2d.h"USING_NS_CC;int main(int argc, char *argv[]){    AppDelegate app;    return Application::getInstance()->run();}

The above Code shows that in main. cpp, two header files are introduced through # include, one is AppDelegate. h and the other is cocos2d. h.

Defines the main entry method of our program, and runs our program by executing the Application: getInstance ()-> run () method.


Next let's take a look at AppDelegate. h and AppDelegate. cpp. The two files are used in Control the entire game Lifecycle.

>>> AppDelegate. h

#ifndef __APP_DELEGATE_H__#define __APP_DELEGATE_H__#include "cocos2d.h"/**@brief    The cocos2d Application.The reason for implement as private inheritance is to hide some interface call by Director.*/class  AppDelegate : private cocos2d::Application{public:    AppDelegate();    virtual ~AppDelegate();    /**    @brief    Implement Director and Scene init code here.    @return true    Initialize success, app continue.    @return false   Initialize failed, app terminate.    */    virtual bool applicationDidFinishLaunching();    /**    @brief  The function be called when the application enter background    @param  the pointer of the application    */    virtual void applicationDidEnterBackground();    /**    @brief  The function be called when the application enter foreground    @param  the pointer of the application    */    virtual void applicationWillEnterForeground();};#endif  // __APP_DELEGATE_H__

>>> AppDelegate. cpp

# Include "AppDelegate. h "# include" CCLuaEngine. h "# include" SimpleAudioEngine. h "# include" cocos2d. h "using namespace CocosDenshion; USING_NS_CC; using namespace std; AppDelegate: AppDelegate () {} AppDelegate ::~ AppDelegate () {SimpleAudioEngine: end ();} bool AppDelegate: applicationDidFinishLaunching () {// initialize director get the director class instance auto Director = director: getInstance (); // obtain the OpenGL instance auto glview = director-> getOpenGLView (); if (! Glview) {// specify the window size. glview = GLView: createWithRect ("HelloLua", Rect (900,640 )); // set OpenGL view ctor-> setOpenGLView (glview);} // set the resolution to 480*320 glview-> setDesignResolutionSize (480,320, ResolutionPolicy: NO_BORDER ); // turn on display FPS to enable the frame rate. Which data string is displayed in the lower-left corner of the screen? // enable FPS display. The current FPS is displayed in the lower-left corner of the game. FPS is the number of times the screen is repainted per second. That is, the frame rate per second. In the game development stage, you can easily determine whether the game is running smoothly. Director-> setDisplayStats (true); // set FPS. the default value is 1.0/60 if you don't call this // set the draw interval director-> setAnimationInterval (1.0/60); // obtain the Lua engine instance auto engine = LuaEngine:: getInstance (); // set the Script engine ScriptEngineManager: getInstance ()-> setScriptEngine (engine); // execute main. lua Script if (engine-> executeScriptFile ("src/main. lua ") {return false;} return true;} // This function will be called when the app is inactive. when comes a phone call, it's be invoked too // When the application is about to enter the background, this method void AppDelegate: applicationDidEnterBackground () {Director: getInstance () -> stopAnimation (); SimpleAudioEngine: getInstance ()-> pauseBackgroundMusic ();} // this function will be called when the app is active again // this method is used with applicationDidEnterBackground () in pairs, void AppDelegate: applicationWillEnterForeground () {Director: getInstance ()-> startAnimation (); SimpleAudioEngine: getInstance () is called when the application returns to the foreground () -> resumeBackgroundMusic ();}

We can find the method to execute our Lua script in the AppDelegate class. Next let's take a look at the main. lua file. The logic implementation displayed on the screen can all be seen in this file:

>>> Main. lua

Require "Cocos2d" require "Cocos2dConstants" -- cclogcclog = function (...) print (string. format (...)) end -- for CCLuaEngine traceback output function _ g1_trackback _ (msg) cclog ("----------------------------------------------") cclog ("lua error :".. tostring (msg ).. "\ n") cclog (debug. traceback () cclog ("----------------------------------------") return msgendlocal function main () collectgarbage ("col Lect ") -- avoid memory leak this is a script reclaim parameter to avoid memory leakage collectgarbage (" setpause ", 100) collectgarbage (" setstepmul ", 5000) -- append the resource search sequence cc. fileUtils: getInstance (): addSearchResolutionsOrder ("src"); cc. fileUtils: getInstance (): addSearchResolutionsOrder ("res"); local schedulerID = 0 -- support debug to obtain the target platform local targetPlatform = cc. application: getInstance (): getTargetPlatform () if (cc. PLATFORM_ OS _IPHONE = targetPlatfo Rm) or (cc. PLATFORM_ OS _IPAD = targetPlatform) or (cc. PLATFORM_ OS _ANDROID = targetPlatform) or (cc. PLATFORM_ OS _WINDOWS = targetPlatform) or (cc. PLATFORM_ OS _MAC = targetPlatform) then cclog ("result is") -- require ('debugger') () end -- similar to c ++ include, introduce files, will check whether repeated introduction of require "hello2" -- call external functions, cclog ("result is" in hello2.lua ".. myadd (1, 1) --------------- obtain the local visibleSize = cc in the visible area. director: getIn Stance (): getVisibleSize () -- the OpenGL Coordinate System of the visual origin coordinate, and the local origin = cc in the lower left corner. director: getInstance (): getVisibleOrigin () -- add the moving dog add the moving squirrel local function creatDog () -- set the size of each frame, local indicates the local variable local frameWidth = 105 local frameHeight = 95 -- create dog animate loads the animation resource and creates the sprite frame -- loads the texture of the sprite animation. local textureDog = cc. director: getInstance (): getTextureCache (): addImage ("dog.png") -- set local rect = cc In the first frame area. rect (0, 0, frameWidth, frameHeight) -- create the first Frame of the genie Frame local frame0 = cc. spriteFrame: createWithTexture (textureDog, rect) -- set rect = cc In the second frame area. rect (frameWidth, 0, frameWidth, frameHeight) -- c creates a second sprite Frame local frame1 = cc. spriteFrame: createWithTexture (textureDog, rect) -- creates a Sprite object local spriteDog = cc based on the first Frame. sprite: createWithSpriteFrame (frame0) spriteDog. isPaused = false spriteDog: setPosition (origin. x, Origin. y + visibleSize. height/4*3) -- [[local animFrames = CCArray: create () animFrames: addObject (frame0) animFrames: addObject (frame1)] ---- create an animation Based on the frame sequence array. The frame interval delay is equal to 0.5 seconds. local animation = cc. animation: createWithSpriteFrames ({frame0, frame1}, 0.5) -- create an action instance local animate = cc Based on the animation Animation. animate: create (animation); -- the squirrel genie executes this action spriteDog: runAction (cc. repeatForever: create (animate) -- moving dog at every frame is used to update the squirrel's location. The local function tick () if spriteDog will be called later. isPaused then return end local x, y = spriteDog: getPosition () if x> origin. x + visibleSize. Width then x = origin. x else x = x + 1 end spriteDog: setPositionX (x) end -- generate a scheule and execute the tick function schedulerID = cc at each frame. director: getInstance (): getScheduler (): scheduleScriptFunc (tick, 0, false) return spriteDog end -- create farm local function createLayerFarm () -- create a new Lyaer for farm management local layerFarm = cc. layer: create () -- add in farm background add farm management local bg = cc. sprite: create ("farm.jpg") bg: se TPosition (origin. x + visibleSize. width/2 + 80, origin. y + visibleSize. height/2) layerFarm: addChild (bg) -- add land sprite add ground brick Block for I = 0, 3 do for j = 0, 1 do local spriteLand = cc. sprite: create ("land.png"), -- set the position of each block spriteLand: setPosition (200 + j * 180-I % 2*90, 10 + I * 95/2) layerFarm: addChild (spriteLand) end -- add crop neural lag, then crop.png is the synthetic texture of multiple images, so only part of the texture inside is taken. local frameCrop = Cc. spriteFrame: create ("crop.png", cc. rect (0, 0,105, 95) for I = 0, 3 do for j = 0, 1 do local spriteCrop = cc. sprite: createWithSpriteFrame (frameCrop); spriteCrop: setPosition (10 + 200 + j * 180-I % 2*90, 30 + 10 + I * 95/2) layerFarm: addChild (spriteCrop) end -- add moving dog call createDog () above, create a moving squirrel local spriteDog = creatDog () layerFarm: addChild (spriteDog) -- handing touch events Finger touch event processing local touchBeginPoint = nil -- click Start local function onTouchBegan (touch, event) local location = touch: getLocation () cclog ("onTouchBegan: % 0.2f, % 0.2f ", location. x, location. y) touchBeginPoint = {x = location. x, y = location. y} -- save the click position spriteDog. isPaused = true -- move the squirrel to pause -- CCTOUCHBEGAN event must return true end -- move the local function onTouchMoved (touch, event) local loca Tion = touch: getLocation () cclog ("onTouchMoved: % 0.2f, % 0.2f", location. x, location. y) if touchBeginPoint then -- drag the entire rural layer because all objects in the farm have been added to layerFarm local cx, cy = layerFarm: getPosition () layerFarm: setPosition (cx + location. x-touchBeginPoint. x, cy + location. y-touchBeginPoint. y) touchBeginPoint = {x = location. x, y = location. y} end -- finger to exit local function onTouchEnded (touch, event) local lo Cation = touch: getLocation () cclog ("onTouchEnded: % 0.2f, % 0.2f", location. x, location. y) touchBeginPoint = nil -- click the position to clear spriteDog. isPaused = false -- Restore squirrel move end -- create a touch event listener local listener = cc. eventListenerTouchOneByOne: create () -- register the touch event listener: registerScriptHandler (onTouchBegan, cc. handler. EVENT_TOUCH_BEGAN) listener: registerScriptHandler (onTouchMoved, cc. handler. EVENT_TOUCH_MOVED) listener: RegisterScriptHandler (onTouchEnded, cc. handler. EVENT_TOUCH_ENDED) local eventDispatcher = layerFarm: getEventDispatcher () -- add scene map priority event listener eventDispatcher: addEventListenerWithSceneGraphPriority (listener, layerFarm) local function onNodeEvent) if "exit" = event then cc. director: getInstance (): getScheduler (): unscheduleScriptEntry (schedulerID) end layerFarm: registerScriptHandler (onNodeEvent) Return layerFarm end -- create menu create interface menu local function createLayerMenu () -- create a new Layer to manage all menus local layerMenu = cc. layer: create () local menuPopup, menuTools, effectID -- click the menu Callback function local function menuCallbackClosePopup () -- stop test sound effect to disable audio cc. simpleAudioEngine: getInstance (): stopEffect (effectID) menuPopup: setVisible (false) -- hide the menu end -- click the menu Callback function local function menuCallbackOpenPopup ()-- Loop test sound effect open local Marketing tpath = cc. fileUtils: getInstance (): fullPathForFilename ("effect1.wav") effectID = cc. simpleAudioEngine: getInstance (): playEffect (effectPath) menuPopup: setVisible (true) end -- add a popup menu to create the pop-up menu panel local menuPopupItem = cc. menuItemImage: create ("menu2.png", "menu2.png") menuPopupItem: setPosition (0, 0) menuPopupItem: registerScriptTapHandler (menuCallbackCloseP Opup) menuPopup = cc. menu: create (menuPopupItem) menuPopup: setPosition (origin. x + visibleSize. width/2, origin. y + visibleSize. height/2) menuPopup: setVisible (false) layerMenu: addChild (menuPopup) -- add the left-bottom "tools" menu to invoke menuPopup -- add the tool button in the lower left corner, used to pop up the menu panel local menuToolsItem = cc. menuItemImage: create ("menu1.png", "menu1.png") menuToolsItem: setPosition (0, 0) -- register click callback address menuToolsI Tem: registerScriptTapHandler (menuCallbackOpenPopup) menuTools = cc. menu: create (menuToolsItem) local itemWidth = menuToolsItem: getContentSize (). width local itemHeight = menuToolsItem: getContentSize (). height menuTools: setPosition (origin. x + itemWidth/2, origin. y + itemHeight/2) layerMenu: addChild (menuTools) return layerMenu end -- play background music, preload effect -- uncomment below for the Blac KBerry version local bgMusicPath = nil if (cc. PLATFORM_ OS _IPHONE = targetPlatform) or (cc. PLATFORM_ OS _IPAD = targetPlatform) then bgMusicPath = cc. fileUtils: getInstance (): fullPathForFilename ("res/background. caf ") else bgMusicPath = cc. fileUtils: getInstance (): fullPathForFilename ("res/background.pdf") end cc. simpleAudioEngine: getInstance (): playMusic (bgMusicPath, true) local variable tpath = cc. fileuiti Ls: getInstance (): fullPathForFilename ("effect1.wav") -- pre-load audio cc. simpleAudioEngine: getInstance (): preloadEffect (effectPath) -- run local sceneGame = cc. scene: create () -- create scenario sceneGame: addChild (createLayerFarm () -- add farm layer to scenario sceneGame: addChild (createLayerMenu ()) -- add the menu interface layer to the scenario -- determine whether a running scenario is available if cc. director: getInstance (): getRunningScene () thencc. director: getInstance (): replaceScene (sceneGame) -- replace elsecc. D Irector: getInstance (): runWithScene (sceneGame) endend -- [xpcall (call function, error capture function); lua provides xpcall to catch exceptions. xpcall accepts two parameters: call functions and error handling functions. When an error occurs, Lua calls the error processing function before the stack is released. Therefore, you can use the debug library to collect error information. Two common debug functions: debug. debug and debug. traceback provides a Lua prompt. You can view the error information by yourself. traceback creates more error information, which is also a function used by the console interpreter to build error information. --] Local status, msg = xpcall (main, _ g1_trackback _) if not status then error (msg) end

This is the code used by the Cocos2d-x 3.1.1, the comments in the Code have been very detailed, the author here not to mention, I hope you can carefully read, with the author as soon as possible to get started Lua in Cocos2dx in use.










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.