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

前端之家收集整理的这篇文章主要介绍了cocos2dx-lua中实现面向对象的封装继承前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

@H_301_432@


2、继承父类

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

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

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

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

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

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

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


3.2、使用方法

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

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

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

> 类的成员变量,均在ctor()中进行声明即可。
原文链接:https://www.f2er.com/cocos2dx/339030.html

猜你在找的Cocos2d-x相关文章