Page 1 of 1

Entity class can't read body variable

Posted: Thu Sep 22, 2022 4:35 pm
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.

Re: Entity class can't read body variable

Posted: Thu Sep 22, 2022 5:38 pm
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)
}