How to obtain a PhysicsBody2D from a RID

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By gcardozo

Hi,

I’m adding a method to Godot source code and I still didn’t figure how to obtain the owner of a given RID and then how to convert it to PhysicsBody2D. The Godot engine development documentation doesn’t cover much about those conversions.

Thanks in advance!

It doesn’t look like you can get the direct Resource for a given RID. From the RID documentation: “They are opaque, so they do not grant access to the associated resource by themselves.” They’re usually used by low-level servers. It may be possible by accessing the PhysicsServer directly. But that’s a whole other can of worms.

Ertain | 2018-10-25 18:36

Yes, I don’t know how to use the RID to obtain a PhysicsBody2D. I have a List<RID> so I suppose it should be something like:

for (List<RID>::Element *E = rid_list.front(); E; E = E->next()) {
    RID body = E->get();
    //somehow obtain the body owner here:
    NoIdeaOfType body_owner = SomehowObtainOwner(body);
    PhysicsBody2D *physics_body = Object::cast_to<PhysicsBody2D>(body_owner);
    //do my stuff with physics_body...
}

gcardozo | 2018-10-25 21:39

I haven’t tried this but maybe Physics2DServer::body_get_object_instance_id(RID) and ObjectDB::get_instance(ObjectID) could help?

indicainkwell | 2018-10-25 22:36

Looks like your suggestion is part of what I needed, thank you so much!
Here’s what I did:

for (List<RID>::Element *E = rid_list.front(); E; E = E->next()) {
	RID body = E->get();
	ObjectID instance_id = Physics2DServer::get_singleton()->body_get_object_instance_id(body);
	Object *obj = ObjectDB::get_instance(instance_id);
	PhysicsBody2D *physics_body = Object::cast_to<PhysicsBody2D>(obj);
	//doing stuff with the physics_body...
}

gcardozo | 2018-10-26 00:06

Awesome, glad I could help. Should I add it as an answer?

indicainkwell | 2018-10-26 00:59

I’ve answered it and referenced your suggestion, thx again! :smiley:

gcardozo | 2018-10-26 01:12

:bust_in_silhouette: Reply From: gcardozo

@IndicaInkWell suggestion was part of the solution, here’s how I did it:

for (List<RID>::Element *E = rid_list.front(); E; E = E->next()) {
	RID body = E->get();
	ObjectID instance_id = Physics2DServer::get_singleton()->body_get_object_instance_id(body);
	Object *obj = ObjectDB::get_instance(instance_id);
	PhysicsBody2D *physics_body = Object::cast_to<PhysicsBody2D>(obj);
	//doing stuff with the physics_body...
}