Godot 如何获取 Colliders Parent Name (C# godot mono v3.1.2 stable)

Godot How to get Colliders Parent Name (C# godot mono v3.1.2 stable)

我有这个代码:

    var Collide = MoveAndCollide(new Vector2(speed.y * (float)Math.Cos(teta), speed.y * (float)Math.Sin(teta)));
    if (Collide != null)
    {
        /* I need to get colliding objects parent node name here*/
    }

这是我的树层次结构:

红色的是正在碰撞的物体。绿色的那个是我想要的字符串格式的名字。

首先看一下 KinematicBody.move_and_collide 的文档:

Returns a KinematicCollision, which contains information about the collision.

KinematicCollision list a number of fields, one of which is collider 的文档:

The colliding body.

注意body是拥有碰撞形状的PhysicsBody不是碰撞形状本身(后者存储在collider_shape).这意味着 collider 将是您示例中的 StaticBody,因此我们可以这样做:

    var Collide = MoveAndCollide(new Vector2(speed.y * (float)Math.Cos(teta), speed.y * (float)Math.Sin(teta)));
    if (Collide != null)
    {
        print(Collide.Collider.Name)
    }

我自己找到了这个有效的解决方案:

    var Collide = MoveAndCollide(new Vector2(speed.y * (float)Math.Cos(teta), speed.y * (float)Math.Sin(teta)));
    //Just defined a MoveAndCollide

    if (Collide != null)
    {
        var x = (Godot.Node2D)Collide.Collider;

        //Use collider as a Godot Node or Node2D
        //then you can access Node properties and method like GetName()

        GD.PrintS(x.GetName()); // Returned speedBoost for me
    }