godotengine / godot-proposals

Godot Improvement Proposals (GIPs)
MIT License
1.07k stars 68 forks source link

RigitBody2D returns (0, 0) as center_of_mass when center_of_mass_mode is AUTO #10037

Open ditiem-games opened 6 days ago

ditiem-games commented 6 days ago

Describe the project you are working on

I have a RigidBody2D that has a block (a simple rectangle) where you can attach other blocks. Attaching a block implies that the collision shape of the added block is added to the RigidBody2D. The RigidBody2D has an script to store the tree of blocks.

Some of these blocks are engines, meaning they can apply a force to the RigidBody2D.

So lets say we name blocks as B, the initial block H, and engines as E . We can have something like:

BHB
E E

Describe the problem or limitation you are having in your project

I noticed that the RigidBody2D is not moving as expected, so I decided to check the center_of_mass to see if Godot was computing it correctly, but I do always get (0, 0). So I cannot debug whether I am putting wrongly the areas or Godot is computing the center wrongly due to whatever reason.

Describe the feature / enhancement and how it helps to overcome the problem or limitation

Currently the C++ code is:

const Vector2 &RigidBody2D::get_center_of_mass() const {
    return center_of_mass;
}

Check it here: https://github.com/godotengine/godot/blob/25ff1306d62b8eb0487608b2a9bed0644e2fce17/scene/2d/physics/rigid_body_2d.cpp#L376C1-L378C2

It should return:

PhysicsServer2D::get_singleton()->body_get_param(get_rid(), PhysicsServer2D::BODY_PARAM_CENTER_OF_MASS )

when the center_of_mass_mode is auto.

Describe how your proposal will work, with code, pseudo-code, mock-ups, and/or diagrams

const Vector2 &RigidBody2D::get_center_of_mass() const {
    if (center_of_mass_mode == CENTER_OF_MASS_MODE_CUSTOM)
        return center_of_mass;

    return PhysicsServer2D::get_singleton()->body_get_param(get_rid(), PhysicsServer2D::BODY_PARAM_CENTER_OF_MASS );
}

If this enhancement will not be used often, can it be worked around with a few lines of script?

Technically yes. It could be solved using PhysicsServer2D.body_get_param() in gdscript.

Is there a reason why this should be core and not an add-on in the asset library?

It is in the core code

Calinou commented 6 days ago

To avoid breaking compatibility, this would need to be added as a new method, as opposed to changing the existing method. Also, get_center_of_mass() is a getter for the center_of_mass property, so it should not return an automatically computed value.

I suggest adding a method like get_effective_center_of_mass() that works as you propose.