Jack Hanson
Jack Hanson

Reputation: 321

Lua LOVE2D can't add more than one bullet to the world using bump

I'm just getting into LOVE2D and making a platformer, but I've hit a snag trying to use the bump library. I have a player that can shoot a bullet and add it to the world just fine when I only shoot once, but when I shoot again LOVE gives me this error:

Error

libs/bump/bump.lua:619: Item table: 0x121b5a18 added to the world twice.

Traceback

[C:]: in function 'error'
libs/bump/bump.lua:619: in function 'add'
main.lua:39: in function 'update'
main.lua:118: in function 'update'
[C:] in function 'xpcall'

My process for adding a bullet to the world is to instantiate the bullet, add it to a table called bullets, then loop through the table add each one to the world.I understand that the problem is that it won't let me add the same item to the world, so my question is how can I add multiple bullets to the world without bump thinking they're the same?

Here is my code for updating the bullets:

function UpdateBullet(dt)
    shootTimer = shootTimer - 1 * dt
    if shootTimer <= 0 then
        player.canShoot = true
    end

    if love.keyboard.isDown("z") and player.canShoot then
        -- instantiate it next to player and a bit up 
        newBullet = {x=player.x + player.width, y = player.y + 5}
        table.insert(bullets, newBullet)
        -- Width and height hardcoded for now
        for i, bullet in ipairs(bullets) do
            world:add(bullet, bullet.x, bullet.y, 10, 10)
        end    
        player.canShoot = false
        shootTimer = player.shootDelay
    end   

    for i, bullet in ipairs(bullets) do
        -- bullet speed and screen size also hardcoded rn, oops
        bullet.x = bullet.x + 250 * dt
        -- if bullet goes off screen, remove it
        if bullet.x > 600 then
            table.remove(bullets, i)
        end
    end
end

I'd appreciate any help. Thanks in advance

Upvotes: 0

Views: 244

Answers (1)

Piglet
Piglet

Reputation: 28964

    for i, bullet in ipairs(bullets) do
        world:add(bullet, bullet.x, bullet.y, 10, 10)
    end

This section of your code adds bullets from a global list. Let's say you have 10 bullets in that list. You add 1 new bullet. Then add these 11 bullets to world. But you already added 10 of those 11 bullets to the world in your last function run.

Upvotes: 2

Related Questions