在我的 Godot 乒乓球游戏中实例化一个球时出错

error with instancing a ball in my pong game in godot

您好,我正在使用 Godot 开发乒乓球游戏。到目前为止一切顺利,但我在调试器中收到此错误:

E 0:01:55.112 body_set_shape_as_one_way_collision: Can't change this state while flushing queries. Use call_deferred() or set_deferred() to change monitoring state instead.

<C++ Error> Condition "body->get_space() && flushing_queries" is true.

<C++ Source> servers/physics_2d/physics_2d_server_sw.cpp:739 @ body_set_shape_as_one_way_collision()

AddBall.gd:18 @ _on_Area2D_body_entered()

这是我实例化一个复制球的代码:

extends Node2D

var collect = false
var ballscene = null

func _ready():
    $Area2D/AnimatedSprite.play("Spin")

func _on_Area2D_body_entered(body):
    #print(body.name)
    if body.name=="Ball"&&collect==false:
        collect = true
        $Collection.play()
        $AnimationPlayer.play("Fade")
        $Area2D/AnimatedSprite.stop()
        var ball =  load("res://Scenes/BallDuplicate.tscn")
        ballscene = ball.instance()
        find_parent("SpawnManager").get_node("BallDuplicate").add_child(ballscene)
        queue_free()
        

是的,我在道具中实例化了球,而不是我的重生管理器。

正如错误消息所建议的那样,您应该使用 call_deffered() 推迟节点树的更改,因为在碰撞处理期间不允许您在场景中添加另一个刚体。

extends Node2D

var collect = false
var ballscene = null

func CollectFunc():
    if not collect:
        collect = true
        $Collection.play()
        $AnimationPlayer.play("Fade")
        $Area2D/AnimatedSprite.stop()
        var ball =  load("res://Scenes/BallDuplicate.tscn")
        ballscene = ball.instance()
        find_parent("SpawnManager").get_node("BallDuplicate").add_child(ballscene)
        queue_free()

func _ready():
    $Area2D/AnimatedSprite.play("Spin")

func _on_Area2D_body_entered(body):
    #print(body.name)
    if body.name=="Ball":
        call_deffered("CollectFunc")