Love2D 错误:main.lua:38:尝试调用方法 'getHeight'(一个 nil 值)



我有一个平台图像加载到Love2D中,它在错误中说:Error: main.lua:38: attempt to call method 'getHeight' (a nil value)下面是我的代码:

platform = love.graphics.newImage("assets/platform.png")
function love.load()
love.window.setTitle("My Platformer")
love.window.setMode(800, 600)
gravity = 800
player = { x = 50, y = 50, speed = 200, jumpHeight = -500, isJumping = false, velocityY = 0, image = love.graphics.newImage("assets/player.png") }

platforms = {
{ x = 0, y = 550 },
{ x = 400, y = 400 },
{ x = 200, y = 300 },
{ x = 600, y = 200 },
{ x = 0, y = 100 },
}
end
function love.update(dt)
-- Apply gravity
player.velocityY = player.velocityY + gravity * dt
player.y = player.y + player.velocityY * dt
-- Jumping
if love.keyboard.isDown("space") and not player.isJumping then
player.isJumping = true
player.velocityY = player.jumpHeight
end
-- Move player left and right
if love.keyboard.isDown("left") then
player.x = player.x - player.speed * dt
elseif love.keyboard.isDown("right") then
player.x = player.x + player.speed * dt
end
-- Detect collisions with platforms
for i, platform in ipairs(platforms) do
if player.y + platform:getHeight() >= platform.y
and player.y <= platform.y + platform:getHeight()
and player.x + player.image:getWidth(help) >= platform.x
and player.x <= platform.x + platform:getWidth() then
player.isJumping = false
player.velocityY = 0
player.y = platform.y - player.image:getHeight()
end
end
end
function love.draw()
-- Draw platforms
for i, platform in ipairs(platforms) do
love.graphics.draw(platform, platform.x, platform.y)
end
-- Draw player
love.graphics.draw(player.image, player.x, player.y)
end

getHeight()在官方文档上,我不明白!是跟站台的形象有关吗?我检查了一下,它存在于我的项目中,所以我的代码有什么问题?

我看了文档,我在网上搜索了错误,什么也没有!

看起来您定义/重新定义了全局变量platforms:

platforms = {
{ x = 0, y = 550 },
{ x = 400, y = 400 },
{ x = 200, y = 300 },
{ x = 600, y = 200 },
{ x = 0, y = 100 },
}

因此,当您使用for i, platform in ipairs(platforms) do ...遍历它时,platform类似于{ x = 0, y = 550 },然后getHeight当然会到达nil,因为这个表只有xy键。

最新更新