{class
Shape 基类(模型)
Circle 子类(圆)
Rectangle 子类(矩形)
main 调用类
继承C++类
}
借鉴 https://blog.csdn.net/u012278016/article/details/79624525
{Shape.lua
--定义名为 Shape 的基础类
local Shape = class("Shape")
--ctor() 是类的构造函数,在调用 Shape.new() 创建 Shape 对象实例时会自动执行
function Shape:ctor(shapeName)
self.shapeName = shapeName;
printf("Shape:ctor(%s)", self.shapeName)
end
--shapeName是类的一个成员变量,在lua中成员变量可以直接通过self.shapeName=shapeName来生成并同时赋值,不用先声明,另外,前面不用local修饰,用local修饰的是局部变量而不是成员变量,成员变量前面用self.
--为 Shape 定义个名为 draw() 的方法
function Shape:draw()
printf("draw %s", self.shapeName)
end
return Shape;
}
{Circle.lua
local Shape=require("example/class/Shape");
--//Circle 是 Shape 的继承类
local Circle = class("Circle", Shape)
function Circle:ctor()
-- 如果继承类覆盖了 ctor() 构造函数,那么必须手动调用父类构造函数
-- 类名.super 可以访问指定类的父类
Circle.super.ctor(self, "circle");
self.radius = 100;
end
function Circle:setRadius(radius)
self.radius = radius
end
--// 覆盖父类的同名方法
function Circle:draw()
printf("draw %s, raidus = %0.2f", self.shapeName, self.radius)
end
return Circle;
}
{Rectangle.lua
local Shape=require("example/class/Shape");
local Rectangle = class("Rectangle", Shape)
function Rectangle:ctor()
Rectangle.super.ctor(self, "rectangle")
end
return Rectangle;
}
{main.lua
local Circle =require "example/class/Circle";
local Rectangle =require "example/class/Rectangle";
local circle = Circle.new() -- Shape:ctor(circle)
circle:setRadius(200)
circle:draw() -- draw circle, raidus = 200.00
local rectangle = Rectangle.new() -- Shape:ctor(rectangle)
rectangle:draw() -- draw rectangle
}
{继承C++类
---@Class Enemy: Sprite
local Enemy=class("Enemy",function ()
local sprite = cc.Sprite:create()
return sprite;
end);
function Enemy:ctor()
Log.debug('enemy.ctor-------');
self.startPosition=cc.p(0,0);--敌人初始化坐标
end
function Enemy:setStartPosition(x,y)
self.startPosition=cc.p(x,y);
Log.debug('\t\tenemyx:'..x);
Log.debug('\t\tenemyy:'..y);
end
function Enemy:toString()
Log.debug('敌人类');
end
return Enemy;
--调用
local Enemy=require("Scene/Enemy/Enemy");
self.enemy=Enemy:create();
self.layer:addChild(self.enemy);
local vvv= cc.Sprite:create("cocosui/sliderballpressed.png")
local spriteFrame= vvv:getSpriteFrame();
self.enemy:setSpriteFrame(spriteFrame);
self.enemy:setPosition(cc.p(display.cx, display.cy));
--其他
class()的这种用法让我们可以在 C++ 对象基础上任意扩展行为。既然是继承,自然就可以覆盖 C++ 对象的方法
local Toolbar = class("Toolbar", function()
return cc.Node:create(); -- 返回一个 CCNode 对象
end)
--构造函数
function Toolbar:ctor()
self.buttons = {} -- 用一个 table 来记录所有的按钮
end
--添加一个按钮,并且自动设置按钮位置
function Toolbar:addButton(button)
--将按钮对象加入 table
self.buttons[#self.buttons + 1] = button
--添加按钮对象到 CCNode 中,以便显示该按钮
--因为 Toolbar 是从 CCNode 继承的,所以可以使用 addChild() 方法
self:addChild(button)
--按照按钮数量,调整所有按钮的位置
local x = 0
for _, button in ipairs(self.buttons) do
button:setPosition(x, 0)
--依次排列按钮,每个按钮之间间隔 10 点
x = x + button:getContentSize().width + 10
end
end
return Toolbar;
}