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

Godot中如何检测触摸屏CollisionPolygon2D区域的2秒长按

Godot中CollisionPolygon2D区域的长按检测实现

针对你的需求,这里提供一种简洁可靠的长按检测方案,核心是利用Godot的Timer节点计时,配合触摸事件状态跟踪:

步骤1:准备Timer节点

在你的节点下添加一个Timer节点(比如命名为long_press_timer),在检查器中设置:

  • Wait Time:2(对应2秒长按时长)
  • One Shot:开启(确保超时后自动停止,不会重复触发)

步骤2:脚本实现逻辑

在绑定了_on_20_Points_input_event信号的脚本里,添加以下代码:

# 记录当前长按的触摸ID(区分多个触摸点)
var active_touch_id: int = -1

func _ready():
    # 绑定Timer的超时信号到长按处理函数
    $long_press_timer.connect("timeout", self, "_on_long_press_triggered")

func _on_20_Points_input_event(viewport, event, shape_idx):
    # 只处理触摸屏触摸事件
    if event is InputEventScreenTouch:
        if event.pressed:
            # 记录当前触摸的ID,启动计时器
            active_touch_id = event.index
            $long_press_timer.start()
        else:
            # 如果是之前记录的触摸点松开,停止计时器并清除记录
            if event.index == active_touch_id:
                $long_press_timer.stop()
                active_touch_id = -1

# 长按触发后的业务逻辑
func _on_long_press_triggered():
    # 执行你的长按操作:加积分、播放动画等
    GlobalVar.points += 20
    refresh_points()
    ani.play("Points_added")
    # 清除触摸记录
    active_touch_id = -1

补充优化:处理触摸移出区域的情况

如果需要在用户按下后移出CollisionPolygon2D区域时取消长按检测,可以添加_process函数做位置校验:

func _process(delta):
    if active_touch_id != -1:
        # 获取当前触摸点的屏幕位置
        var touch_pos = get_viewport().get_input_position(active_touch_id)
        # 转换为节点本地坐标
        var local_pos = get_global_transform().affine_inverse() * touch_pos
        # 检查位置是否在CollisionPolygon2D的形状范围内
        if not $CollisionPolygon2D.shape.is_point_inside(local_pos):
            $long_press_timer.stop()
            active_touch_id = -1

这个方案逻辑清晰,通过触摸ID跟踪确保多触摸场景下的准确性,避免了你之前代码中复杂的位置列表判断,完全符合Godot的官方推荐用法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 23:40:23