I have been trying to split a game object in half, starting with splitting the collision shape in half. I create two new clones of the split object, then give them a property to be assigned to the collision polygon. In the editor, the setup looks like this:
The health_xxx are sprites to be changed based on how damaged it is. In code, I do this:
// two paths created from the original shape
std::array<PackedVector2Array*, 2> paths {&path1, &path2};
for (const auto* path : paths)
{
ShootableObject* myCopy = (ShootableObject*)duplicate(DUPLICATE_SIGNALS & DUPLICATE_SCRIPTS);
// this is the path to be assigned when the object is ready
myCopy->collisionOverride = *path;
get_parent()->add_child(myCopy);
}
In _ready
, I tried to do find_child
and Object::cast_to
, but that doesn't work. The following code works and demonstrates my problem:
if (collisionOverride.size() > 0)
{
CollisionPolygon2D* collision = Object::cast_to<CollisionPolygon2D>(find_child("collision"));
if (collision)
{
// never happens
collision->set_polygon(collisionOverride);
}
else
{
UtilityFunctions::print("Cannot override collision, node not found! Trying alternative method");
for (int i = 0; i < get_child_count(); ++i)
{
Node* child = get_child(i);
if (child->get_name() != StringName("collision"))
{
continue;
}
if (collision = Object::cast_to<CollisionPolygon2D>(child))
{
// this works
collision->set_polygon(collisionOverride);
UtilityFunctions::print("Success.");
break;
}
}
}
}
The output I get:
Cannot override collision, node not found! Trying alternative method
Success.
I just don't understand why do I have to reimplement find_child
in this case. Even stranger is the fact that for nodes that exist from the start, this is not a problem.
I am using Godot 4.2.
find_child("collision",false,false)
insdead. \$\endgroup\$