From 6a05825b24cfbec683f8f5ab7c49b7faf2bfefae Mon Sep 17 00:00:00 2001 From: thiagola92 Date: Mon, 14 Aug 2023 16:43:22 -0300 Subject: [PATCH] Refactor function `calculate_length_and_rotation()` from Skeleton2D --- scene/2d/skeleton_2d.cpp | 32 +++++++++++++------------------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/scene/2d/skeleton_2d.cpp b/scene/2d/skeleton_2d.cpp index 527bbaf9565..4f747b276e7 100644 --- a/scene/2d/skeleton_2d.cpp +++ b/scene/2d/skeleton_2d.cpp @@ -433,29 +433,23 @@ PackedStringArray Bone2D::get_configuration_warnings() const { } void Bone2D::calculate_length_and_rotation() { - // if there is at least a single child Bone2D node, we can calculate + // If there is at least a single child Bone2D node, we can calculate // the length and direction. We will always just use the first Bone2D for this. - bool calculated = false; int child_count = get_child_count(); - if (child_count > 0) { - for (int i = 0; i < child_count; i++) { - Bone2D *child = Object::cast_to(get_child(i)); - if (child) { - Vector2 child_local_pos = to_local(child->get_global_position()); - length = child_local_pos.length(); - bone_angle = child_local_pos.normalized().angle(); - calculated = true; - break; - } + Transform2D global_inv = get_global_transform().affine_inverse(); + + for (int i = 0; i < child_count; i++) { + Bone2D *child = Object::cast_to(get_child(i)); + if (child) { + Vector2 child_local_pos = global_inv.xform(child->get_global_position()); + length = child_local_pos.length(); + bone_angle = child_local_pos.angle(); + return; // Finished! } } - if (calculated) { - return; // Finished! - } else { - WARN_PRINT("No Bone2D children of node " + get_name() + ". Cannot calculate bone length or angle reliably.\nUsing transform rotation for bone angle"); - bone_angle = get_transform().get_rotation(); - return; - } + + WARN_PRINT("No Bone2D children of node " + get_name() + ". Cannot calculate bone length or angle reliably.\nUsing transform rotation for bone angle."); + bone_angle = get_transform().get_rotation(); } void Bone2D::set_autocalculate_length_and_angle(bool p_autocalculate) {