Rigid body Mass Center API

I wrote a script attempting to print the mass center of a rigid body, but encountered an error as shown in the attachment. The error message is: “
center of Mass for cube is at: invalid attribute “physics:centerOfMass” on “cube” prim <World/Xform/Cube> on stage with root Layer @anon:0x1b1b8af0:World0.usd@, sessionLayr@anon:0x1bd05700:World0-session.usda@


printMassCenter.txt (1.4 KB)

. Could you please advise where the problem is?

Hi,
I think your problem is that the MassAPI is not on the prim, you can adjust the script to something like this to check:

import omni
from pxr import UsdPhysics, UsdGeom

def find_and_display_rigidbody_center_of_mass():
# 获取当前场景的 Stage
    stage = omni.usd.get_context().get_stage()
    if not stage:
        print("No active stage.")
        return

# 获取当前选中的对象
    selection = omni.usd.get_context().get_selection()
    selected_paths = selection.get_selected_prim_paths()

    if not selected_paths:
        print("No object selected.")
        return

    for path in selected_paths:
        # 获取选中对象的 Prim
        prim = stage.GetPrimAtPath(path)

        # 确保选中的 Prim 是一个 RigidBody
        if not prim or not UsdPhysics.RigidBodyAPI(prim):
            print(f"The selected object at {path} is not a RigidBody.")
            continue

        # 获取质心信息(不用rigid body API, 而是用Mass API )
        if prim.HasAPI(UsdPhysics.MassAPI):
            mass_api = UsdPhysics.MassAPI(prim)
            print(mass_api)
            apis = prim.GetAppliedSchemas()
            print(apis)
            center_of_mass_attr = mass_api.GetCenterOfMassAttr()

            # 打印质心位置
            print(f"Center of Mass for {prim.GetName()} is at: {center_of_mass_attr}")
        else:
            print("No mass API")

# 可视化质心位置(可选)
# 这里你可以添加代码来创建一个可视化的标记(如一个小球或点)在质心位置

# 调用函数
find_and_display_rigidbody_center_of_mass()

Regards
Ales

Thank you Ales. I got it. Not every rigid body has MassAPI. ^_^

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.