新建一个lua工程,打开cmd命令控制台,切换到cocos2d-x2.1.4/tools/project-creator/下,输入以下命令:
D:\Python275\python create_project.py -project GyenLua -package com.gyen.org.gyenlua -language lua
代码如下:
AppDelegate.cpp
#include "cocos2d.h"
#include "CCEGLView.h"
#include "AppDelegate.h"
#include "CCLuaEngine.h"
#include "SimpleAudioEngine.h"
#include "Lua_extensions_CCB.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#include "Lua_web_socket.h"
#endif
using namespace CocosDenshion;
USING_NS_CC;
AppDelegate::AppDelegate()
{
}
AppDelegate::~AppDelegate()
{
SimpleAudioEngine::end();
}
bool AppDelegate::applicationDidFinishLaunching()
{
// initialize director
CCDirector *pDirector = CCDirector::sharedDirector();
pDirector->setOpenGLView(CCEGLView::sharedOpenGLView());
// turn on display FPS
pDirector->setDisplayStats(true);
// set FPS. the default value is 1.0/60 if you don't call this
pDirector->setAnimationInterval(1.0 / 60);
// register lua engine
CCLuaEngine* pEngine = CCLuaEngine::defaultEngine();
CCScriptEngineManager::sharedManager()->setScriptEngine(pEngine);
CCLuaStack *pStack = pEngine->getLuaStack();
lua_State *tolua_s = pStack->getLuaState();
tolua_extensions_ccb_open(tolua_s);
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
pStack = pEngine->getLuaStack();
tolua_s = pStack->getLuaState();
tolua_web_socket_open(tolua_s);
#endif
std::string path = CCFileUtils::sharedFileUtils()->fullPathForFilename("hello.lua");
pEngine->executeScriptFile(path.c_str());
return true;
}
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground()
{
CCDirector::sharedDirector()->stopAnimation();
SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground()
{
CCDirector::sharedDirector()->startAnimation();
SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
}
hello.lua代码如下:
require "AudioEngine"
-- 输出绑定执行函数发生错误的信息
function __G__TRACKBACK__(msg)
print("----------------------------------------")
print("LUA ERROR: " .. tostring(msg) .. "\n")
print(debug.traceback())
print("----------------------------------------")
end
local function main()
-- 设置脚本内存回收参数 避免内存泄露
collectgarbage("setpause", 100)
collectgarbage("setstepmul", 5000)
-- 就是local function cclog(...) 定义局部Log函数
local cclog = function(...)
print(string.format(...))
end
-- 类似c++的include,会检查是否重复引入
require "hello2"
cclog("result is " .. myadd(3, 5))
---------------
-- 获取可视区域
local visibleSize = CCDirector:sharedDirector():getVisibleSize()
-- 可视原点坐标 OpenGL坐标系 左下角为原点
local origin = CCDirector:sharedDirector():getVisibleOrigin()
-- 创建小松鼠
local function creatDog()
-- 每一帧尺寸设置,local表示局部变量
local frameWidth = 105
local frameHeight = 95
-- 加载动画资源并创建精灵帧
local textureDog = CCTextureCache:sharedTextureCache():addImage("dog.png")
-- 设置第一帧帧区域
local rect = CCRectMake(0, 0, frameWidth, frameHeight)
-- 创建第一帧精灵Frame
local frame0 = CCSpriteFrame:createWithTexture(textureDog, rect)
-- 设置第二帧帧区域
rect = CCRectMake(frameWidth, 0, frameWidth, frameHeight)
-- 创建第二帧精灵Frame
local frame1 = CCSpriteFrame:createWithTexture(textureDog, rect)
-- 基于使用第一帧Frame创建Sprite对象
local spriteDog = CCSprite:createWithSpriteFrame(frame0)
spriteDog.isPaused = false
spriteDog:setPosition(origin.x, origin.y + visibleSize.height / 4 * 3)
-- 将上面创建的两帧生成一个帧数组(这个松鼠一共就2帧)
local animFrames = CCArray:create()
animFrames:addObject(frame0)
animFrames:addObject(frame1)
-- 根据帧序列数组创建一个动画animation。帧间隔时间delay等于0.5秒
local animation = CCAnimation:createWithSpriteFrames(animFrames, 0.5)
-- 根据动画animation创建动作实例
local animate = CCAnimate:create(animation);
-- 松鼠精灵执行该动作
spriteDog:runAction(CCRepeatForever:create(animate))
-- 用来更新松鼠的位置,后面会调用该函数
local function tick()
if spriteDog.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
-- 生成一个schedule,每帧执行tick函数
CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(tick, 0, false)
return spriteDog
end
-- 创建地面的农场
local function createLayerFarm()
-- 创建一个新的Layer用作农场管理
local layerFarm = CCLayer:create()
-- 添加农场背景图
local bg = CCSprite:create("farm.jpg")
bg:setPosition(origin.x + visibleSize.width / 2 + 80, origin.y + visibleSize.height / 2)
layerFarm:addChild(bg)
-- 添加地面砖块
for i = 0, 3 do
for j = 0, 1 do
local spriteLand = CCSprite:create("land.png")
spriteLand:setPosition(200 + j * 180 - i % 2 * 90, 10 + i * 95 / 2)
layerFarm:addChild(spriteLand)
end
end
-- 添加庄稼,注意crop.png是多张图的合成贴图,所以只取了里面的部分贴图
local frameCrop = CCSpriteFrame:create("crop.png", CCRectMake(0, 0, 105, 95))
for i = 0, 3 do
for j = 0, 1 do
local spriteCrop = CCSprite:createWithSpriteFrame(frameCrop);
spriteCrop:setPosition(10 + 200 + j * 180 - i % 2 * 90, 30 + 10 + i * 95 / 2)
layerFarm:addChild(spriteCrop)
end
end
-- 调用上面的creatDog()方法,创建一个移动的松鼠
local spriteDog = creatDog()
layerFarm:addChild(spriteDog)
-- 手指触摸事件处理
local touchBeginPoint = nil
-- 手指点击开始
local function onTouchBegan(x, y)
cclog("onTouchBegan: %0.2f, %0.2f", x, y)
-- 保存点击位置
touchBeginPoint = {x = x, y = y}
-- 将松鼠暂停移动
spriteDog.isPaused = true
-- 这里必须返回ture,否则后续touch事件无法接收
return true
end
-- 手指按住移动
local function onTouchMoved(x, y)
cclog("onTouchMoved: %0.2f, %0.2f", x, y)
if touchBeginPoint then
-- 将整个农场层拖动,因为之前已经将农场里面所有对象加入在layerFarm
local cx, cy = layerFarm:getPosition()
layerFarm:setPosition(cx + x - touchBeginPoint.x,
cy + y - touchBeginPoint.y)
touchBeginPoint = {x = x, y = y}
end
end
-- 手指离开
local function onTouchEnded(x, y)
cclog("onTouchEnded: %0.2f, %0.2f", x, y)
-- 点击位置数据清空
touchBeginPoint = nil
-- 恢复松鼠移动
spriteDog.isPaused = false
end
-- touch事件的接收函数
local function onTouch(eventType, x, y)
if eventType == "began" then
return onTouchBegan(x, y)
elseif eventType == "moved" then
return onTouchMoved(x, y)
else
return onTouchEnded(x, y)
end
end
-- 注册touch事件
layerFarm:registerScriptTouchHandler(onTouch)
layerFarm:setTouchEnabled(true)
return layerFarm
end
-- 创建界面菜单
local function createLayerMenu()
-- 创建一个新的CCLayer管理所有菜单
local layerMenu = CCLayer:create()
local menuPopup, menuTools, effectID
-- 点击菜单回调函数
local function menuCallbackClosePopup()
-- 关闭音效
AudioEngine.stopEffect(effectID)
menuPopup:setVisible(false)
end
-- 点击菜单回调函数
local function menuCallbackOpenPopup()
-- 打开音效
local effectPath = CCFileUtils:sharedFileUtils():fullPathForFilename("effect1.wav")
effectID = AudioEngine.playEffect(effectPath)
-- 显示菜单
menuPopup:setVisible(true)
end
-- 创建弹出的菜单面板
local menuPopupItem = CCMenuItemImage:create("menu2.png", "menu2.png")
menuPopupItem:setPosition(0, 0)
-- 注册点击回调地址
menuPopupItem:registerScriptTapHandler(menuCallbackClosePopup)
menuPopup = CCMenu:createWithItem(menuPopupItem)
menuPopup:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2)
menuPopup:setVisible(false)
layerMenu:addChild(menuPopup)
-- 左下角的工具按钮,用来弹出菜单面板
local menuToolsItem = CCMenuItemImage:create("menu1.png", "menu1.png")
menuToolsItem:setPosition(0, 0)
-- 注册点击回调地址
menuToolsItem:registerScriptTapHandler(menuCallbackOpenPopup)
menuTools = CCMenu:createWithItem(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
-- 播放背景音乐
local bgMusicPath = CCFileUtils:sharedFileUtils():fullPathForFilename("bg_music.mid")
AudioEngine.playMusic(bgMusicPath, true)
-- 预加载音效
local effectPath = CCFileUtils:sharedFileUtils():fullPathForFilename("effect1.wav")
AudioEngine.preloadEffect(effectPath)
-- 创建场景
local sceneGame = CCScene:create()
-- 将农场层加入场景
sceneGame:addChild(createLayerFarm())
-- 将菜单界面层加入场景
sceneGame:addChild(createLayerMenu())
-- 启动场景
CCDirector:sharedDirector():runWithScene(sceneGame)
end
-- xpcall( 调用函数, 错误捕获函数 )
-- lua提供了xpcall来捕获异常
-- xpcall接受两个参数:调用函数、错误处理函数。
-- 当错误发生时,Lua会在栈释放以前调用错误处理函数,因此可以使用debug库收集错误相关信息。
-- 两个常用的debug处理函数:debug.debug和debug.traceback
-- 前者给出Lua的提示符,你可以自己动手察看错误发生时的情况;
-- 后者通过traceback创建更多的错误信息,也是控制台解释器用来构建错误信息的函数。
xpcall(main, __G__TRACKBACK__)
hello2.lua代码如下:
function myadd(x, y)
return x + y
end
运行效果: