加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

cocos2dx-lua中实现面向对象的封装继承

发布时间:2020-12-14 17:15:26 所属栏目:百科 来源:网络整理
导读:class函数 是在"cocos2d-x-3.2/cocos/scripting/lua-bindings/script/extern.lua"中定义的。 -- Create an class. function class(classname,super) local superType = type (super) local cls if superType ~= "function" and superType ~= "table" then su

class函数是在"cocos2d-x-3.2/cocos/scripting/lua-bindings/script/extern.lua"中定义的。


-- Create an class.

functionclass(classname,super)

localsuperType =type(super)

localcls


ifsuperType ~= "function"andsuperType ~= "table"then

superType =nil

super =nil

end


ifsuperType == "function"or(superandsuper.__ctype == 1)then

-- inherited from native C++ Object

cls = {}


ifsuperType == "table"then

-- copy fields from super

fork,vinpairs(super)docls[k] = vend

cls.__create = super.__create

cls.super = super

else

cls.__create = super

end


cls.ctor =function()end

cls.__cname = classname

cls.__ctype = 1


functioncls.new(...)

localinstance = cls.__create(...)

-- copy fields from class to native object

in pairs(cls)doinstance[k] = vend

instance.class = cls

instance:ctor(...)

returninstance

else

-- inherited from Lua Object

ifsuperthen

cls =clone(super)

cls.super = super

else

cls = {ctor =end}

end


cls.__cname = classname

cls.__ctype = 2-- lua

cls.__index = cls


localinstance =setmetatable({},cls)

instance.class = cls

instance:end

returncls

end


在Lua中类的概念就是table表,而上面的函数代码主要做的就是对父类super的表进行拷贝,然后再定义了两个函数cls.new(...)cls:ctor(...)。如果我们不了解上面的代码,也是没有关系的,只要我们会使用它就够了。

0、使用方法

>定义一个类:cls =class("类名","父类")

> 创建实例 :obj = cls.new()

>初始化函数:cls:ctor()在创建实例的时候,会自动调用

只要掌握这三步骤,对于我们cocos2d-x的开发已经够用了!

1、创建基类

首先创建一个Hero类,然后重写Hero类的初始化函数Hero:ctor()

再创建一个Hero类的实例对象Hero.new(),会自动调用初始化函数Hero:ctor() 。

测试输出。

注意:其中ctor()中出现的self为实例对象本身,就相当于C++类中的this



2、继承父类

在cocos2d-x开发中,经常需要继承引擎中的类,如Layer、Sprite等。

这里举例,将上面的Hero类修改一下,继承自Sprite

3、再举个例子:继承Layer类

我一般习惯在ctor()中只声明一些类的成员变量。

然后再自定义一个函数create(),将new()进行封装,然后在 create() 中调用init()函数进行实例对象的初始化工作。

这样的好处就是:在使用上就和我在C++中的使用的方式一样了。

3.1、定义一个继承于Layer的类


3.2、使用方法

> 创建包含GameLayer层的Scene场景:GameLayer:createScene()

> 创建一个GameLayer层-----------:GameLayer:create()

> 而在创建GameLayer时,也会调用自定义的初始化函数init()

> 类的成员变量,均在ctor()中进行声明即可。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读