How to set the center of gravity for a RigidBody2D?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By potato
:warning: Old Version Published before Godot 3 was released.

I am trying to make a game where the player can place items on a raft arbitrarily which should impact it’s center of gravity.

The raft is a RigidBody2D with a single collision object. I can iterate through the raft and the items on the raft to calculate the point where the center of gravity should be set to. Is there either a way to get this to happen automatically, or a function that will allow me to set the CoG?

Alternatively, I suppose I could use an extra node to offset all the RigidBody’s children in the opposite direction, but that seems gross and I’m concerned the movement of the collision object might cause the CoG to change.

The RigidBodies Center of Gravity will indeed change if you put another RigidBody on it. Like you expect it in the real world. This is because the items will push with their gravity force on the rafts rigidbody. Just be sure to define the Rigidbody mass values accordingly.

I’ve some buoyancy code with damping in this demo here:
Loading...

Just in case you need code for the floating raft. That demo is for 2.1.4, but I can provide it also for 3 alpha if required.

wombatstampede | 2017-09-20 08:17

Thanks for your comment!

Are you saying that I can add other rigid bodies as children, and they’ll effect the center of mass of the parent - or just that rigid bodies interacting can have the same effect?

To clarify, my goal is that the items on the raft be fixed to the raft, such that I move the overall raft to move all the items (no sliding around).

potato | 2017-09-20 16:08

It doesn’t seem to matter physics-wise if other RigidBodies are children or not. They effect the center of mass of the RigidBody they’re physically on. But they’re “loose”.

If you want to prevent sliding around, you can experiment joining the bodies with “Joints”.

But if you already found a satisfying workaround then you may as well stick with that. Joints/Rigidbodies/Collision shapes can be tricky to handle and may unnecessarily consume cpu time.

wombatstampede | 2017-09-25 07:39

:bust_in_silhouette: Reply From: mollusca

It seems a RigidBody2D’s center of gravity is always at the origin of the RigidBody2D, so instead of setting the CG directly you have to offset the shape(s) of the body. In your case maybe you could calculate the new CG, move the shape so it matches the wanted CG position and then move the RigidBody2D an opposite but equal amount so the shape ends up back in it’s original world position.

Thanks, I tried hacking this in and it works for now!

potato | 2017-09-19 19:19