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

如何在Godot中将CharacterBody2D的jetpack_fuel变量显示到Label?

实现喷气背包燃料值显示到Label上

要将CharacterBody2D中的jetpack_fuel变量值显示到Camera2D子节点的Label上,只需两步修改:

1. 获取Label节点引用

在脚本的@onready区域添加Label节点的路径引用(Label是Camera2D的子节点,路径为$Camera2D/jetpack_fuel):

@onready var sprite_2d = $Sprite2D
@onready var fuel_label = $Camera2D/jetpack_fuel  # 新增:获取Label节点

2. 实时更新Label文本

在_physics_process函数末尾添加更新Label文本的代码,将jetpack_fuel的值格式化后显示(这里取整为整数,避免显示过多小数):

func _physics_process(delta):
    _jump(delta)
    _walking_n_running()
    _running()
    _flip()
    move_and_slide()
    sprite_2d.animation = animation
    # 新增:更新燃料显示
    fuel_label.text = "喷气燃料: %d" % jetpack_fuel.floor()

修改后的完整代码

extends CharacterBody2D

var speed = 200
const jump_velocity = -400
var direction = Vector2()
var jetpack_fuel = 100
var jetpacking = false
@onready var sprite_2d = $Sprite2D
@onready var fuel_label = $Camera2D/jetpack_fuel  # 获取Label节点

var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
var animation = 'idle'

func _jetpacking(delta):
    if Input.is_action_pressed("Jump") and jetpack_fuel > 0:
        velocity.y = jump_velocity * 0.5 
        jetpack_fuel -= 10 * delta 
        animation = 'jetpacking' 
    else:
        velocity.y += gravity * delta 
        if not is_on_floor():
            animation = 'jumping' 

func _walking_n_running():
    direction = Input.get_axis("GoLeft", "GoRight")
    if direction != 0:
        velocity.x = direction * speed
        if speed > 200 and is_on_floor():
            animation = "running"
        if speed <= 200 and is_on_floor():
            animation = "walking"
    else:
        velocity.x = move_toward(velocity.x, 0, 16)
        if is_on_floor():
            animation = "idle"  

func _jump(delta):
    jetpacking = true
    if is_on_floor() and Input.is_action_just_pressed("Jump"):
        velocity.y = jump_velocity
        animation = 'jumping'
        jetpacking = false
    elif not is_on_floor():
        _jetpacking(delta)
func _running():
    if Input.is_action_pressed('Sprint'):
        speed = 280
    else:
        speed = 200

func _flip():
    if Input.is_action_just_pressed('GoLeft'):
        sprite_2d.flip_h = true
    if Input.is_action_just_pressed('GoRight'):
        sprite_2d.flip_h = false

func _physics_process(delta):
    _jump(delta)
    _walking_n_running()
    _running()
    _flip()
    move_and_slide()
    sprite_2d.animation = animation
    # 更新燃料显示
    fuel_label.text = "喷气燃料: %d" % jetpack_fuel.floor()

如果需要保留一位小数,可以把格式化字符串改成"喷气燃料: %.1f",根据需求调整即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:42:34