尝试对空值进行自我索引

我正在为项目制作一个 powerup 类,在尝试运行时,我会得到一个错误,说“尝试对空值进行自我索引”。我真的很感激如果有人能帮助我。谢谢阅读!

PS:是的,我在 Render、Init、Update 函数中使用冒号而不是点号。


function Powerup:init()
    -- 简单的位置和维度变量
    self.x = x
    self.y = y
    self.width = 11
    self.height = 11


    self.dy = 0
    self.dx = 0

    self.inPlay = true
end

--[[
    预期接收一个 bounding box 参数,可能是挡板或砖头,
    如果此对象和参数的边界框重叠,则返回 true。
]]
function Powerup:collides(target)

    if self.x > target.x + target.width or target.x > self.x + self.width then
        return false
    end

    if self.y > target.y + target.height or target.y > self.y + self.height then
        return false
    end


    return true
end

function Powerup.trigger(paddle)
    if self.inPlay then
     self.inPlay = false
    end
end

function Powerup:update(dt)
    self.x = self.x
    self.y = self.y + self.dy * dt


    if self.y <= 0 then
        self.y = 0
        self.dy = -self.dy
        gSounds['wall-hit']:play()
    end
end

function Powerup:render()

    if self.inPlay then
       love.graphics.draw('zucc.png', self.x, self.y)
   end
end```
点赞
用户12568711
用户12568711

table.method(self) 等同于 table:method(),两者都将 self 作为第一个参数传入,这意味着如果你使用冒号 :,你不需要声明 self 作为一个参数。

如果这并没有解决你的问题,能否更详细地告诉我们哪一行导致了错误?

编辑:

导致错误的原因是您没有声明变量 xy 作为参数。错误提示是“你正在尝试将 self 的索引 x 的值插入 x,但变量 X 并不存在,也就是说,你正在尝试将 nil 插入变量中”

您可以通过在函数中声明参数来解决此问题:

Powerup:init(x, y)

然后调用该函数,给出值 xy,例如:

Powerup:init(3,5)

现在 self.x 是 3,self.y 是 5。

2020-08-20 16:06:25