Elwood
Elwood

Reputation: 1

How to make bullets appear on the screen (Lua, Love2D)

I am making a 2d game about dodging bullets in space. I am trying to do so bullets spawn at random locations on the top of the screen and fall down to the bottom so the player can dodge them. Here is my code so far:

function love.load()
timer = 0

background = love.graphics.newImage("space_background.png")

bullet = {
    x = 300,
    y = 0,
    image = love.graphics.newImage("bullet.png"),
    width = love.graphics.getWidth(image),
    height = love.graphics.getHeight(image),
    speed = 10  }

listOfBullets = {}

car = {
    x = 100,
    y = 100,
    size = 5,
    angle = 0,
    image = love.graphics.newImage("classic_car.png")
}
end

function love.update(dt)
    timer = timer + dt

    if love.keyboard.isDown("left") then
        car.x = car.x - 200 * dt
    end

    if love.keyboard.isDown("right") then
        car.x = car.x + 200 * dt
    end

    if love.keyboard.isDown("up") then
        car.y = car.y - 200 * dt 
    end
    
    if love.keyboard.isDown("down") then
        car.y = car.y + 200 * dt
    end

    car.angle = car.angle + 1 * dt

    if love.keyboard.isDown("r") then
        timer = 0
        car.x = 100
        car.y = 100
        car.angle = 0
    end

    table.insert(listOfBullets, math.random(1, 799), bullet.y)

    for i,v in ipairs(listOfBullets) do
        v:update(dt)
    end
end

function love.draw()
    love.graphics.draw(background, 0, 0)
    love.graphics.print({"Score: " .. math.floor(timer), white}, 20, 550, 0, 2)
    love.graphics.draw(car.image, car.x, car.y, 
        car.angle, 1, 1, car.image:getWidth()/2, car.image:getHeight()/2)
    for i,v in pairs(listOfBullets) do
        love.graphics.print(v, 100, 100)
    end
end

Every time I try to run the programm it gives me the same error and I have no idea what it means or how to solve it:

Error

main.lua:77: attempt to index local 'v' (a number value)

Traceback

main.lua:77: in function 'update'

[C]: in function 'xpcall'

Can anyone please help me?

Upvotes: 0

Views: 131

Answers (1)

luther
luther

Reputation: 5564

The error message says that v is a number. The colon notation entails getting the value v.update, which is an indexing operation, but it's not possible to index numbers.

So why is v a number?

This can be explained by reading the doc for table.insert. In the statement table.insert(listOfBullets, math.random(1, 799), bullet.y), you're inserting bullet.y, which is 0, into random indexes inside listOfBullets.

I don't know what you were trying to do there, but I think your next step towards working code would be to define a constructor function that creates new bullets and change your insert call to something like:

table.insert(listOfBullets, newBullet())

Upvotes: 1

Related Questions