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

Godot子弹场景实例化问题:仅能创建单颗子弹

Godot子弹实例化问题:单次发射限制解决方法

问题描述

在Godot中创建子弹场景实例时,最初使用.new()或.instance()报错,改用.instantiate()后无报错,但曾出现子弹显示极小、移动缓慢的问题(已自行解决)。目前遇到核心问题:每次仅能创建一颗子弹。

现有代码

子弹代码(Area2D)

extends Area2D

var speed = -2400
var target = position

func ready():
    rotation = get_global_mouse_position().angle_to_point(position)
    
func _physics_process(delta):
    position += transform.x * speed * delta
    

func _on_body_entered(body):
    if body.name == "Dummy":
        body.queue_free()
        queue_free()

枪支代码(Sprite2D)

extends Sprite2D

var bullet = preload("res://scenes/bullet.tscn").instantiate()

func _ready():
    pass
    
func shoot():
    add_child(bullet)

func _physics_process(_delta):
    rotation = get_global_mouse_position().angle_to_point(position)
    if Input.is_action_just_pressed("input_use_click"):
        shoot()

问题原因

枪支代码中提前实例化了单个bullet对象,每次调用shoot()只是尝试将同一个子弹节点重复添加到场景树。但Godot中一个节点不能同时存在于场景树的多个位置,也无法重复添加同一个节点,因此实际只有第一次添加生效,后续点击不会生成新子弹。

解决方法

不要提前实例化子弹,而是预加载子弹场景资源,在每次调用shoot()时动态创建新的子弹实例:

修改后的枪支代码

extends Sprite2D

# 仅预加载场景资源,不提前实例化
var bullet_scene = preload("res://scenes/bullet.tscn")

func _ready():
    pass
    
func shoot():
    # 每次射击时创建新的子弹实例
    var new_bullet = bullet_scene.instantiate()
    add_child(new_bullet)
    # 可选:让子弹从枪支位置出发
    new_bullet.global_position = global_position

func _physics_process(_delta):
    rotation = get_global_mouse_position().angle_to_point(position)
    if Input.is_action_just_pressed("input_use_click"):
        shoot()

补充优化

如果需要让子弹继承枪支的旋转角度,可在创建实例后添加:

new_bullet.global_rotation = global_rotation

内容的提问来源于stack exchange,提问作者monkie-dev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 17:19:59