Lua 怎样才能访问父节点?

我在制作一个游戏,在其中玩家需要生成一些子弹:

game
├──player = {}
└──bullets = {}

我听说 Godot 中可以使用 parent 来访问父节点,想知道我是否可以以某种方式模仿它。

我目前有两个潜在解决方案:

local game = {
    player = player.new(x, y, spawnBullet),
    bullets = {}
}

其中 spawnBullet 是一个函数。尽管这需要对所有函数执行此操作,但可能会很麻烦。

我的第二个解决方案是将 game 本身传递给玩家:

local game
game = {
    player = player.new(x, y, game),
    bullets = {},

player.new(x, y, parent) 中:

player.parent = parent

这是所有可用的解决方案吗,还是有更好的解决方案?

不管怎样,我自己制作了一个节点模块。

local node = {}
node.__index = node

local new = function(name, parent)
    assert(name, "请提供节点名称")
    local newNode = {
        name = name,
        parent = parent,
    }
    return setmetatable(newNode, node)
end

return setmetatable(
    {
        new = new,
        __call = new,
    },
    node
)
点赞
用户870125
用户870125

你使用的是引擎/框架吗?

我使用的是gideros,我的方式是这样的,示例:

主游戏

  • 我的玩家
  • 子弹

在我的玩家类中:

-- 开火
if self.isspace then
    local bullet = Character_Bullet.new(self.world, ...)
    self:getParent():addChild(bullet)
    self.isspace = false
end

```

2020-06-07 19:13:18