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

Godot4中如何从玩家脚本修改触碰触发的进度条数值?

Godot4:玩家脚本触发碰撞时修改进度条数值

这里给你几个直接可用的实现方案,都是针对Godot4的:

1. 先搞定进度条的引用

首先得让玩家脚本能找到进度条节点,两种常用方式:

  • 可视化绑定:在玩家节点的脚本里定义变量@export var progress_bar: ProgressBar,然后在编辑器里把进度条节点拖到这个变量的赋值框里。
  • 路径查找:如果进度条在UI根节点下,用@onready var progress_bar = $"/root/UI/ProgressBar"(路径要对应你的项目实际结构)。

2. 碰撞触发时修改数值

根据你用的玩家节点类型选对应的方法:

用Area2D做玩家/碰撞检测

Area2D自带body_entered信号,直接监听碰撞:

extends Area2D

@export var progress_bar: ProgressBar

func _ready():
    # 连接碰撞信号到处理函数
    body_entered.connect(_on_collectible_touched)

func _on_collectible_touched(body):
    # 只处理目标物体,比如名字叫Collectible的道具
    if body.name == "Collectible":
        # 增加进度条数值,这里设为每次加10
        progress_bar.value += 10
        # 限制数值不超过进度条最大值
        progress_bar.value = min(progress_bar.value, progress_bar.max_value)
        # 销毁捡取的道具
        body.queue_free()

用CharacterBody2D做玩家

CharacterBody2D可以在物理帧里检测碰撞:

extends CharacterBody2D

@export var progress_bar: ProgressBar
@export var move_speed: float = 300.0

func _physics_process(delta):
    var input_dir = Input.get_vector("left", "right", "up", "down").normalized()
    velocity = input_dir * move_speed

    # 移动并检测碰撞
    var collision = move_and_collide(velocity * delta)
    if collision:
        var touched_body = collision.get_collider()
        if touched_body.name == "Collectible":
            progress_bar.value += 10
            progress_bar.value = min(progress_bar.value, progress_bar.max_value)
            touched_body.queue_free()

3. 关键注意点

  • 检查碰撞层和掩码:玩家节点的碰撞掩码要包含目标物体的碰撞层,不然碰了也检测不到。
  • 进度条的最大值:在编辑器里给ProgressBar的max_value设好(比如100),避免数值溢出。
  • 如果是全局UI:可以把UI节点设为AutoLoad,这样玩家脚本里直接用全局变量引用,比如GlobalUI.progress_bar.value +=10。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 02:33:13