Bjørn Pollen
Bjørn Pollen

Reputation: 63

How can I edit the transform component of a child entity?

I have a TextBundle as a Children of an Entity with a SpriteBundle. I want to change the transform of both of these in a query, I tried something like this:

mut query: Query<(Entity, &Creature, &mut Transform)>
mut child_query: Query<&Children>

I can then get the child entity with:

for (entity, creature, mut transform) in query.iter_mut() {
    // edit transform of creature
    for child in child_query.iter_descendants(entity) {
        // How can i get the transform component of this child entity?
    }
}

How can I edit the transform component of this child entity?

Upvotes: 0

Views: 119

Answers (1)

kmdreko
kmdreko

Reputation: 60497

If you are only interested in the direct children then you don't want iter_descendents since that will return the children, but also the children's children, and so on. To get the direct children of an entity, you just need to get the &Children for it; no separate query.

However, you will need to have a different query for what you want to get from the children since Children only provides the entity handles. So you'll want something like this:

mut query: Query<(Entity, &Creature, &mut Transform, &Children)>, // for SpriteBundle entities
mut child_query: Query<&mut Transform, Without<Creature>>,        // for TextBundle entities

I added Without<Creature> since you said you want to mutate both, but Rust won't let you access the same entity mutably twice. Your sets are probably distinct, but this convinces Bevy that they are distinct and thus allows you to mutate through both. You can change this to a better identifying component if you wish.

Then the code would be like this:

for (entity, creature, mut transform, children) in query.iter_mut() {
    // edit transform of creature
    for child_transform in child_query.iter_many_mut(children) {
        // edit transform component of the child
    }
}

I didn't actually check that this compiles or works. I'll see if I can validate it later, but the concept should be sound.

Upvotes: 2

Related Questions