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

Love2D中实现与isDown等效的触摸持续触发功能咨询

实现Love2D触摸按钮按住持续开火

我来帮你搞定这个触摸持续开火的问题!在Love2D里,触摸和鼠标的触发逻辑不一样——鼠标按住时我们可以在循环里检测状态,但触摸只有touchpressed和touchreleased两个单次事件,所以得通过跟踪触摸状态+在update循环里检测的方式来实现持续开火。

核心思路

  1. 用一个表记录当前处于按住状态的触摸ID(每个触摸都有唯一ID,不会冲突)
  2. 在触摸按下时标记该触摸为激活状态,同时触发第一次开枪(避免延迟)
  3. 在触摸松开时取消该触摸的激活状态
  4. 在love.update里循环检查激活的触摸,只要满足条件就持续触发开枪(记得加冷却控制频率)

完整代码示例

首先定义全局变量来维护状态:

-- 存储当前按住的触摸ID
activeTouches = {}
-- 枪械冷却参数:控制开枪频率
fireCooldown = 0
fireRate = 0.1 -- 每0.1秒开一枪(每秒10次)

然后处理触摸按下/松开事件:

function love.touchpressed(id, x, y, dx, dy, pressure)
    -- 假设你的开火按钮是屏幕左下角100x100的区域,根据自己的UI调整坐标
    local buttonX1, buttonX2 = 0, 100
    local buttonY1, buttonY2 = love.graphics.getHeight() - 100, love.graphics.getHeight()
    
    -- 判断触摸是否在按钮区域内
    if x >= buttonX1 and x <= buttonX2 and y >= buttonY1 and y <= buttonY2 then
        activeTouches[id] = true -- 标记该触摸为激活
        
        -- 立即开一枪,避免按住后第一枪有延迟
        if fireCooldown <= 0 then
            fireGun()
            fireCooldown = fireRate
        end
    end
end

function love.touchreleased(id, x, y, dx, dy, pressure)
    -- 触摸松开时,从激活表中移除该ID
    activeTouches[id] = nil
end

接下来在love.update里处理持续开火逻辑:

function love.update(dt)
    -- 更新冷却时间
    if fireCooldown > 0 then
        fireCooldown = fireCooldown - dt
    end

    -- 检查是否有触摸按住开火按钮
    local isHoldingFire = false
    for touchId, _ in pairs(activeTouches) do
        -- 再次检查触摸位置(防止手指滑出按钮后还继续开火)
        local touchX, touchY = love.touch.getPosition(touchId)
        local buttonX1, buttonX2 = 0, 100
        local buttonY1, buttonY2 = love.graphics.getHeight() - 100, love.graphics.getHeight()
        
        if touchX >= buttonX1 and touchX <= buttonX2 and touchY >= buttonY1 and touchY <= buttonY2 then
            isHoldingFire = true
            break
        end
    end

    -- 如果按住按钮且冷却完成,触发开枪
    if isHoldingFire and fireCooldown <= 0 then
        fireGun()
        fireCooldown = fireRate
    end
end

最后是你的开枪逻辑函数(根据自己的游戏需求修改):

function fireGun()
    -- 这里写具体的开枪逻辑:生成子弹、播放音效、扣减弹药等
    print("Bang! 开了一枪")
end

关键细节说明

  • 触摸ID跟踪:每个触摸都有唯一ID,所以即使多个手指触摸屏幕,也能精准区分哪个是按住开火按钮的手指。
  • 冷却机制:必须加冷却时间,不然每帧都会触发开枪,导致子弹泛滥甚至性能问题。
  • 位置二次检查:在love.update里再次检查触摸位置,能避免用户手指不小心滑出按钮区域后,游戏还继续开火的问题,提升操作体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:09:08