》》main.cpp
#include “AppDelegate.h”
#include “cocos2d.h”
USING_NS_CC;
int main(int argc, char *argv[])
{
AppDelegate app;
return Application::getInstance()->run();
}
以上代码我们可以看到,在main.cpp里,通过#include引入了两个头文件,一个是AppDelegate.h、一个是cocos2d.h。
定义了我们程序的入口方法main,通过执行Application::getInstance()->run()方法来运行我们的程序。
接着我们来看AppDelegate.h和AppDelegate.cpp,这里两个文件用于 控制整个游戏的生命周期。
>>>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 获得导演类实例
auto director = Director::getInstance();
// 获得OpenGL实例
auto glview = director->getOpenGLView();
if(!glview) {
// 指定窗口大小
glview = GLView::createWithRect(“HelloLua”, Rect(0,0,900,640));
// 设置OpenGL视图
director->setOpenGLView(glview);
}
// 设置分辨率大小为480*320
glview->setDesignResolutionSize(480, 320, ResolutionPolicy::NO_BORDER);
// turn on display FPS 打开帧频,屏幕左下角哪一串数据
// 启用FPS 显示,当前 FPS 会在游戏的左下角显示。FPS也就是屏幕每秒重绘的次数。即每秒帧速率。在游戏开发阶段,可以方便地确定游戏运行是否流畅。
director->setDisplayStats(true);
// set FPS. the default value is 1.0/60 if you don’t call this
// 设置绘制间隔
director->setAnimationInterval(1.0 / 60);
// 获得Lua引擎实例
auto engine = LuaEngine::getInstance();
// 设置脚本引擎
ScriptEngineManager::getInstance()->setScriptEngine(engine);
// 执行main.lua脚本
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
// 当应用程序将要进入后台时,会调用这个方法
void AppDelegate::applicationDidEnterBackground()
{
Director::getInstance()->stopAnimation();
SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}
// this function will be called when the app is active again
// 该方法与applicationDidEnterBackground() 成对出现,在应用程序回到前台时被调用
void AppDelegate::applicationWillEnterForeground()
{
Director::getInstance()->startAnimation();
SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}
我们在AppDelegate类当中可以找到执行我们Lua脚本的方法,下面来看一下main.lua这个文件,我们屏幕显示的逻辑实现全部在这个文件中可以看到:
>>>main.lua
require “Cocos2d”
require “Cocos2dConstants”
– cclog
cclog = function(…)
print(string.format(…))
end
– for CCLuaEngine traceback 输出绑定执行函数发生错误的信息
function G__TRACKBACK(msg)
cclog(“----------------------------------------”)
cclog("LUA ERROR: " … tostring(msg) … “\n”)
cclog(debug.traceback())
cclog(“----------------------------------------”)
return msg
end
local function main()
collectgarbage(“collect”)
– avoid memory leak 这是脚本回收参数,避免内存泄漏
collectgarbage(“setpause”, 100)
collectgarbage(“setstepmul”, 5000)
– 追加资源的搜索顺序
cc.FileUtils:getInstance():addSearchResolutionsOrder(“src”);
cc.FileUtils:getInstance():addSearchResolutionsOrder(“res”);
local schedulerID = 0
–support debug 获取目标平台
local targetPlatform = cc.Application:getInstance():getTargetPlatform()
if (cc.PLATFORM_OS_IPHONE == targetPlatform) 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
– 类似c++的include,引入文件,会检查是否重复引入
require “hello2”
– 调用外部函数,在hello2.lua中
cclog("result is " … myadd(1, 1))
– 获取可视区域
local visibleSize = cc.Director:getInstance():getVisibleSize()
– 可视原点坐标 OpenGL坐标系,左下角为原点
local origin = cc.Director:getInstance():getVisibleOrigin()
– add the moving dog 添加移动的小松鼠
local function creatDog()
– 每一帧尺寸设置,local表示局部变量
local frameWidth = 105
local frameHeight = 95
– create dog animate 加载动画资源并创建精灵帧
– 加载精灵动画所在纹理
local textureDog = cc.Director:getInstance():getTextureCache():addImage(“dog.png”)
– 设置第一帧帧区域
local rect = cc.rect(0, 0, frameWidth, frameHeight)
– 创建第一帧精灵Frame
local frame0 = cc.SpriteFrame:createWithTexture(textureDog, rect)
– 设置第二帧帧区域
rect = cc.rect(frameWidth, 0, frameWidth, frameHeight)
– c创建第二帧精灵Frame
local frame1 = cc.SpriteFrame:createWithTexture(textureDog, rect)
– 基于使用第一帧Frame创建Sprite对象
local spriteDog = cc.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)
]]–
– 根据帧序列数组创建一个动画animation。帧间隔时间delay等于0.5秒
local animation = cc.Animation:createWithSpriteFrames({frame0,frame1}, 0.5)
– 根据动画animation创建动作实例
local animate = cc.Animate:create(animation);
– 松鼠精灵执行该动作
spriteDog:runAction(cc.RepeatForever:create(animate))
– moving dog at every frame 用来更新松鼠的位置,后面会调用该函数
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
– 生成一个scheule,每帧执行tick函数
schedulerID = cc.Director:getInstance():getScheduler():scheduleScriptFunc(tick, 0, false)
return spriteDog
end
– create farm 创建地面的农场
local function createLayerFarm()
– 创建一个新的Lyaer用作农场管理
local layerFarm = cc.Layer:create()
– add in farm background 添加农场管理
local bg = cc.Sprite:create(“farm.jpg”)
bg:setPosition(origin.x + visibleSize.width / 2 + 80, origin.y + visibleSize.height / 2)
layerFarm:addChild(bg)
– add land sprite 添加地面砖块
for i = 0, 3 do
for j = 0, 1 do
local spriteLand = cc.Sprite:create(“land.png”)、
– 设定每一块砖块位置
spriteLand:setPosition(200 + j * 180 - i % 2 * 90, 10 + i * 95 / 2)
layerFarm:addChild(spriteLand)
end
end
– add crop 添加庄稼,注意crop.png是多张图的合成贴图,所以只取了里面的部分贴图
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
end
– add moving dog 调用上面的createDog()方面,创建一个移动的松鼠
local spriteDog = creatDog()
layerFarm:addChild(spriteDog)
– handing touch events 手指触摸事件处理
总结
本文讲解了我对Android开发现状的一些看法,也许有些人会觉得我的观点不对,但我认为没有绝对的对与错,一切交给时间去证明吧!愿与各位坚守的同胞们互相学习,共同进步!
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!