Entity class can't read body variable

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
Sammm
Prole
Posts: 37
Joined: Fri Sep 09, 2022 4:39 pm

Entity class can't read body variable

Post by Sammm »

Hello!

I have an object called "entity" with a function called "entity.spawn." Inside that function the data for the x, y, sprite, and id (for multiplayer) is stored. However, when I want to add a body for my entity, I get an error when trying to attach the body to the fixture, stating,
Bad argument #1 to newFixture (Body expected, got nil)
Here's my code for that:

Code: Select all

local entity = {}
entity.entities = {} --All entities

entity.spawn = function(id, x, y)
    local sprites = {
        blueSprite,
        yellowSprite,
        redSprite,
        purpleSprite,
    }
    return {
        sprite = sprites[(tonumber(id) % #sprites) + 1],
        id = id,
        x = x,
        y = y,
        body = love.physics.newBody(world, x, y, "dynamic"),
        shape = love.physics.newCircleShape(50),
        fixture = love.physics.newFixture(body, shape)
    }
end
What am I doing wrong? Sorry if this is a dumb error, I'm quite new to how Lua works.
Lua is LÖVE, lua is life
User avatar
ReFreezed
Party member
Posts: 612
Joined: Sun Oct 25, 2015 11:32 pm
Location: Sweden
Contact:

Re: Entity class can't read body variable

Post by ReFreezed »

'body'' and 'shape' are not variables in the function - they are fields in the table that you return. Move the body and shape creation to before the return statement to solve the issue:

Code: Select all

local body = love.physics.newBody(world, x, y, "dynamic")
local shape = love.physics.newCircleShape(50)
return {
    sprite = sprites[(tonumber(id) % #sprites) + 1],
    id = id,
    x = x,
    y = y,
    body = body,
    shape = shape,
    fixture = love.physics.newFixture(body, shape)
}
Tools: Hot Particles, LuaPreprocess, InputField, (more) Games: Momento Temporis
"If each mistake being made is a new one, then progress is being made."
Post Reply

Who is online

Users browsing this forum: No registered users and 12 guests