本節介紹給節點加組件(其實就是一個lua腳本)的方式。
C++代碼如下:
#include "CCComponentLua.h"
bool HelloWorld::init()
{
if ( !Scene::init() )
{
return false;
}
auto visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
auto closeItem = MenuItemImage::create("CloseNormal.png","CloseSelected.png",CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
float x = origin.x + visibleSize.width - closeItem->getContentSize().width/2;
float y = origin.y + closeItem->getContentSize().height/2;
closeItem->setPosition(Vec2(x,y));
auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);
//給當前scene添加一個lua腳本組件
this->addComponent(ComponentLua::create("test.lua"));
return true;
}
Lua代碼:
-- scene.lua
require "cocos.init"
local scene = {
onEnter = function(self)
local visibleSize = cc.Director:getInstance():getVisibleSize()
--創建精靈
local sprite = cc.Sprite:create("HelloWorld.png")
sprite:setPosition(visibleSize.width/2, visibleSize.height/2)
self:getOwner():addChild(sprite)
--觸摸處理
local function touchBeganCallBack(touch, event)
print("touchBegan")
local location = touch:getLocation()
sprite:setPosition(location)
return true
end
local function touchMovedCallBack(touch, event)
print("touchMoved")
local location = touch:getLocation()
sprite:setPosition(location)
end
local function touchEndedCallBack(touch, event)
print("touchEnded")
local location = touch:getLocation()
sprite:setPosition(location)
end
--設置觸摸監聽
local listener = cc.EventListenerTouchOneByOne:create()
listener:registerScriptHandler(touchBeganCallBack, cc.Handler.EVENT_TOUCH_BEGAN)
listener:registerScriptHandler(touchMovedCallBack, cc.Handler.EVENT_TOUCH_MOVED)
listener:registerScriptHandler(touchEndedCallBack, cc.Handler.EVENT_TOUCH_ENDED)
cc.Director:getInstance():getEventDispatcher():addEventListenerWithSceneGraphPriority(listener, self:getOwner())
end,
onExit = function(self)
end,
update = function(self)
end
}
return scene
在lua腳本中有三個函數onEnter、onExit、update,熟悉C++版本的人就應該知道Node類中也有這三個函數, 當這個腳本掛在某個Node上面之後,引擎底層C++部分在觸發這三個函數的時候,就會相應觸發本節點上所掛腳本的對應函數。
底層源碼部分展示:
在Node的OnEnter函數中,會遍歷這個節點上所有腳本,並觸發腳本中的OnEnter函數。
如果熟悉Cocos Creator就會發現,這種使用lua腳本的方式和creator掛載js(ts)腳本很相似。只不過creator是用可視化編輯器創建節點,拖拽掛載腳本;而我們使用C++代碼創建節點和綁定腳本,殊途同歸!