尝试对字段(nil值)执行算术运算



我有一个播放器对象,它将一个项目符号添加到ListOfBullets

function Player:keyPressed(key)
--If the spacebar is pressed
if key == "space" then
--Put a new instance of Bullet inside listOfBullets.
table.insert(ListOfBullets, Bullet(self.x, self.y, self.state))
end
end


main更新并绘制这里列表中的每个项目符号

function love.update(dt)
Player:update(dt)
Enemy:update(dt)
for i,v in ipairs(ListOfBullets) do
v:update(dt)


end
end

子弹看起来像这样,并实现如下:https://github.com/rxi/classic



function Bullet:new(xpos,ypos,state)
self.x = xpos
self.y = ypos
self.state = state
self.speed = 700
self.r = 10
end
function Bullet:update(dt)
self.y = self.y + self.speed*dt

end
function Bullet:draw()
love.graphics.setColor(0,0,0,1)
love.graphics.circle("fill", self.x, self.y, self.r)
end
一般来说,当我遇到这个问题时,编程初学者正在遵循简单游戏设计教程由于某种原因,y和x都是nil,我不知道为什么,我在哪里做错了

不确定如何声明Bullet(因为它必须像函数一样具有元表)

我想,在Bullet:new函数中,您想要创建一个新的子弹作为新对象(或表)。但你没有返回任何东西,你只是赋值给self。这行不通,因为你想要退回一颗新子弹。所以正确的代码应该是这样的:

local Bullet = {}
Bullet.__index = Bullet
function Bullet.new(xpos, ypos, state) -- also notice, that for new, you use . and not : as you are only creating new object, if you would use self, you would assign values to Bullet, not you newly created bullet
local self = setmetatable({}, Bullet) -- you can also declare x, y, ... in this table too
self.x = xpos
self.y = ypos
self.state = state
self.speed = 700
self.r = 10
return bullet
end
-- and your other functions
function Bullet:update(dt)
self.y = self.y + self.speed*dt
end

然后,你可以像使用

一样使用它
local myBullet = Bullet.new(1, 2, 'test')
myBullet:update(dt)
有关Lua中面向对象编程的更多信息,请参阅Lua -users wiki

最新更新