You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Love2D制作射击游戏:love.keyboard.isDown无法添加子弹求助

问题分析与修复方案

核心问题

  • bullets 列表被反复清空:每次创建新子弹时,Bullet:new() 里的 bullets={} 都会重置整个子弹列表,导致刚插入的子弹立刻被清空。
  • 发射逻辑放错位置:在单个子弹的 update 方法里处理新子弹创建,意味着每帧每个已存在的子弹都会尝试生成新子弹,同时每次生成都会触发列表重置,完全无法积累子弹。

修复步骤

1. 正确初始化子弹列表

把 bullets={} 移到 main.lua 的全局作用域(或 love.load() 函数内),彻底移除 Bullet:new() 里的列表重置代码:

-- main.lua
bullets = {} -- 全局初始化子弹列表

function love.load()
    -- 这里放player、facingL等初始化代码
end

function love.update(dt)
    -- 把发射逻辑移到这里
    if love.keyboard.isDown("space") then
        table.insert(bullets, Bullet())
    end

    -- 更新所有子弹
    for i,v in ipairs(bullets) do
        v:update(dt)
    end
end

function love.draw()
    for i,v in ipairs(bullets) do
        v:draw()
    end
end

2. 修正 Bullet 类代码

移除构造函数里的列表重置,只保留子弹自身的属性初始化:

-- bullet.lua
Bullet=Object:extend()
function Bullet:new()
    self.image=love.graphics.newImage("sprite/bullet.png")
    self.x=player.x
    self.y=player.y
    self.spd=800
    -- 删除此行:bullets={}
end

function Bullet:draw()
    if facingL then
        love.graphics.draw(self.image,self.x+20,self.y+20)
    else
        love.graphics.draw(self.image,self.x,self.y+20)
    end
end

function Bullet:update(dt)
    local vx=0
    -- 删除这里的发射逻辑
    if facingL then
        vx=self.spd*-1
    else
        vx=self.spd
    end
    
    self.x=self.x+vx*dt
end

3. 可选:添加连射冷却(避免按住空格疯狂生成子弹)

如果需要限制发射频率,可在 main.lua 里加计时器:

-- main.lua
bullets = {}
canShoot = true
shootCooldown = 0.2 -- 每0.2秒允许发射一次
shootTimer = 0

function love.update(dt)
    shootTimer = shootTimer + dt
    if shootTimer >= shootCooldown then
        canShoot = true
    end

    if love.keyboard.isDown("space") and canShoot then
        table.insert(bullets, Bullet())
        canShoot = false
        shootTimer = 0
    end

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

补充说明

love.keypressed 能正常工作的原因是它只在按键按下的单帧触发,且如果当时发射逻辑是放在 main.lua 的 love.keypressed 里,不会触发 Bullet:new() 里的列表重置,所以子弹能被正确保存。

内容的提问来源于stack exchange,提问作者Hoooly Kuashi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 20:27:49