I'm starting a new game divided into several files, but I don't know exactly how to reference the anim8 library in it.
When running the project below, the message "Error: player.lua:44: attempt to index field 'anim' (a nil value)" is displayed.
I know it's something simple, but I'm a bit lost... I appreciate any help.
main.lua
Code: Select all
require 'intro'
require 'menu'
require 'level1'
function love.load()
scene = intro
if scene == intro then
intro:load()
elseif scene == menu then
menu:load()
elseif scene == level1 then
level1:load()
end
end
function love.update(dt)
if scene == intro then
intro:update(dt)
elseif scene == menu then
menu:update(dt)
elseif scene == level1 then
level1:update(dt)
end
end
function love.draw()
if scene == intro then
intro:draw()
elseif scene == menu then
menu:draw()
elseif scene == level then
level:draw()
end
end
Code: Select all
intro = {}
function intro:load()
-- body
end
function intro:update(dt)
if love.keyboard.isDown('return') then
scene = menu
end
end
function intro:draw()
love.graphics.print("Intro. Press ENTER to Menu", 100, 100)
end
Code: Select all
menu = {}
function menu:load()
-- body
end
function menu:update(dt)
if love.keyboard.isDown('x') then
scene = level1
end
end
function menu:draw()
love.graphics.print("Menu. Press X to Start", 100, 100)
end
Code: Select all
player = {}
anim8 = require 'anim8'
function player:load()
player.img = love.graphics.newImage('sprites/player-frame-1.png')
player.spriteSheet = love.graphics.newImage('sprites/player.png')
player.grid = anim8.newGrid(44, 64, player.spriteSheet:getWidth(), player.spriteSheet:getHeight())
player.animations = {}
player.animations.right = anim8.newAnimation(player.grid('1-4', 1), 0.2)
player.animations.left = anim8.newAnimation(player.grid('1-4', 2), 0.2)
player.anim = player.animations.right
player.width = love.graphics.getWidth()
player.height = love.graphics.getHeight()
player.x = 200
player.y = 200
player.speed = 300
end
function player:update(dt)
player:move(dt)
end
function player:move(dt)
local isMoving = false
if love.keyboard.isDown('right') then
if player.x < (love.graphics.getWidth() - player.img:getWidth()) then
player.x = player.x + player.speed * dt
player.anim = player.animations.right
isMoving = true
end
end
if love.keyboard.isDown('left') then
if player.x > 0 then
player.x = player.x - player.speed * dt
player.anim = player.animations.left
isMoving = true
end
end
if isMoving == false then
player.anim:gotoFrame(1)
end
player.anim:update(dt)
end
function player:draw()
player.anim:draw(player.spriteSheet, player.x, player.y)
end
Code: Select all
level1 = {}
require 'player'
function level1:load()
player:load()
end
function level1:update(dt)
player:update(dt)
end
function level1:draw()
love.graphics.print("Game is running!", 100, 100)
player:draw()
end