美文网首页
10.Quick-cocos2dx组件编程

10.Quick-cocos2dx组件编程

作者: 会写诗的翩翩少年 | 来源:发表于2017-08-01 15:57 被阅读0次

0.前言
本文为学习笔记,并非教程!!!

--使self对象获得组件的方法,执行完此句后,self对象便可执行EventProtocol中的方法了
cc(self):addComponent("components.behavior.EventProtocol"):exportMethods()

1.给游戏对象添加组件相关方法
cc的元表为ccmt,ccmt实现了元方法__call,所以cc(self)即为GameObject.extend(self)

--src\framework\cc\init.lua
local GameObject = cc.GameObject
local ccmt = {}
ccmt.__call = function(self, target)
    if target then
        return GameObject.extend(target)
    end
    printError("cc() - invalid target")
end
setmetatable(cc, ccmt)

GameObject.extend(self)的实现如下,也就是给self对象添加操作组件的相关方法

--src\framework\cc\GameObject.lua
local Registry = import(".Registry")

local GameObject = {}

function GameObject.extend(target)
    target.components_ = {}

    function target:checkComponent(name)
        return self.components_[name] ~= nil
    end

    function target:addComponent(name)
        local component = Registry.newObject(name)
        self.components_[name] = component
        component:bind_(self)
        return component
    end

    function target:removeComponent(name)
        local component = self.components_[name]
        if component then component:unbind_() end
        self.components_[name] = nil
    end

    function target:getComponent(name)
        return self.components_[name]
    end

    return target
end

return GameObject

2.添加组件

    function target:addComponent(name)
        --根据组件名返回组件对象
        local component = Registry.newObject(name)
        self.components_[name] = component
        component:bind_(self)
        return component
    end

根据组件名返回组件对象

--src\framework\cc\Registry.lua
function Registry.newObject(name, ...)
    local cls = Registry.classes_[name]
    if not cls then
        -- auto load
        pcall(function()
            cls = require(name)
            Registry.add(cls, name)
        end)
    end
    assert(cls ~= nil, string.format("Registry.newObject() - invalid class \"%s\"", tostring(name)))
    return cls.new(...)
end

组件指定绑定的对象,并让对象添加该组件依赖的组件

function Component:bind_(target)
    self.target_ = target
    for _, name in ipairs(self.depends_) do
        if not target:checkComponent(name) then
            target:addComponent(name)
        end
    end
    self:onBind_(target)
end

3.将组件方法暴露给对象
完成以下方法后,游戏对象便可操作组件的方法

function Component:exportMethods_(methods)
    self.exportedMethods_ = methods
    local target = self.target_
    local com = self
    for _, key in ipairs(methods) do
        if not target[key] then
            local m = com[key]
            target[key] = function(__, ...)
                return m(com, ...)
            end
        end
    end
    return self
end

相关文章

网友评论

      本文标题:10.Quick-cocos2dx组件编程

      本文链接:https://www.haomeiwen.com/subject/bubjlxtx.html