Love2D 错误:main.lua:38:尝试调用方法“getHeight”(零值)

问题描述 投票:0回答:1

我在 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()
在官方文档上,我不明白!与平台形象有关吗?我检查过它存在于我的项目中,那么我的代码有什么问题吗?

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

lua love2d
1个回答
0
投票

看起来你定义/重新定义了全局变量

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
,因为这个表只有键
x
y

© www.soinside.com 2019 - 2024. All rights reserved.