我不太確定代碼現在發生了什么。它都是在 VScode 中用 Lua 撰寫的,所以我一直只使用 Alt L 來運行它的 love 擴展,因為我實際上沒有設定 Lua 編譯器。當我運行代碼時,我的想法是我將點擊螢屏,子彈會朝那個方向移動,然后在 0.5 秒后它就會消失。
然而,發生的事情是,在我產生子彈后,它會存在一段時間(我認為是 0.5 秒,但我不太確定)然后自行移除。這就是我想要的,但是我為找到子彈應該行進的方向并將其應用于它的 x 和 y 值而進行的計算繼續發生,即使子彈從表中移除。我不確定這個術語,而且我只使用了 LOVE 一兩天,所以我不太清楚發生了什么。
這是代碼:
function love.load()
window = {}
window.x, window.y = love.graphics.getDimensions()
player = {}
player.speed = 5
player.x = window.x/2
player.y = window.y/2
player.r = 15
player.w = {15, 0.5} --speed, duration
bullets = {} --x, y, direction, speed, duration
direction = 0
end
function love.update(dt)
for i=1, #bullets do
bullets[i][1] = bullets[i][1] bullets[i][4]*math.cos(bullets[i][3])
bullets[i][2] = bullets[i][2] bullets[i][4]*math.sin(bullets[i][3])
bullets[i][5] = bullets[i][5] - dt
if bullets[i][5] <= 0 then
table.remove(bullets, i)
end
end
end
function love.draw()
love.graphics.circle('fill', player.x, player.y, player.r)
love.graphics.print(direction)
love.graphics.print('('..love.mouse.getX()..','..love.mouse.getY()..')',0,50)
love.graphics.print('('..player.x..','..player.y..')',0,100)
for i=1, #bullets do
love.graphics.circle('fill', bullets[i][1], bullets[i][2], 5)
end
end
function love.mousepressed(x, y, button, istouch, presses)
if button == 1 then
direction = math.atan((y-player.y)/(x-player.x))
if player.x > x then direction = direction math.pi end
direction = direction math.random(-10, 10) * math.pi/180
table.insert(bullets, {player.x, player.y, direction, player.w[1],player.w[2]})
end
end
當我運行它并執行我之前所說的操作時,這是我收到的錯誤:
Error
main.lua:18: attempt to index a nil value
Traceback
main.lua:18: in function 'update'
[C]: in function 'xpcall'
第 18 行是這樣的: bullets[i][1] = bullets[i][1] bullets[i][4]*math.cos(bullets[i][3])
我從來沒有真正用 Lua 開發過,這是我第一次進入游戲開發領域,所以我只是在試驗,因此可能撰寫的代碼非常糟糕。我感謝任何幫助,謝謝!
uj5u.com熱心網友回復:
在數字for回圈中,在回圈的第一次迭代之前,控制運算式只計算一次。通過table.remove在回圈中呼叫,您在已經評估bullets之后縮短#bullets,因此它嘗試讀取不再存在的元素。(并且您還為您洗掉的每個元素跳過了一個元素。)在這種情況下,為了快速解決這兩個問題,您可以使用for i=#bullets, 1, -1 dofor 您的回圈。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/357321.html
