lualove2d

Love2D Error: main.lua:38: attempt to call method 'getHeight' (a nil value)


I have a platform image loaded into Love2D, and it says in the error: Error: main.lua:38: attempt to call method 'getHeight' (a nil value) Here is my code:

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() is on the official documentation, I don't get it! Is it something with the platform image? I checked and it exists in my project, so what is wrong with my code?

I looked through the documentation, I searched the error on the web, nothing!


Solution

  • It looks like you defined/redefined the global variant platforms with:

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

    Therefore, when you traverse it using for i, platform in ipairs(platforms) do ..., the platform is something like { x = 0, y = 550 }, then of course getHeight comes to nil because this table only have keys x and y.