#How to move a entity towards another entity?

1 messages · Page 1 of 1 (latest)

sinful shuttle
#

I have two entity that both have a Transform component (I call them Entity A and Entity B). How could I move Entity A towards Entity B without rotating it? I think I do not need to make a MRE for this. Thanks! :)

lean sandal
#
transform.translation = transform.translation.lerp(
    other_transform.translation,
    factor
);
#

You can lerp one translation towards the other

#

If you want to animate it you can do it gradually over time

#
transform.translation = transform.translation.lerp(
    other_transform.translation,
    MOVEMENT_SPEED * time.delta_seconds()
);
#

factor is just a float - so 0.5 will get you halfway there

sinful shuttle
#

Thank you!

dusk heron
#

That can be good for some things, but be aware that if you are using the current location as the starting value for lerp, it will take a long time or never reach the destination as it gets slower and slower the closer it is since you are moving a percentage of the distance between them every frame.
If you want to just move a set amount towards the other entity instead, you can use something like this (use with transform.translation):

/// Moves a point towards a target point by a maximum distance.
fn move_towards(start: Vec3, target: Vec3, max_distance: f32) -> Vec3 {
    let a = target - start;
    let magnitude = a.length();
    if magnitude <= max_distance || magnitude == 0.0 {
        target
    } else {
        start + a / magnitude * max_distance
    }
}

Or if you want to use an easing algorithm but still want it to actually reach it's destination, you could look at https://crates.io/crates/bevy_tweening It works because it keeps track of the animation's starting location instead of using the current location.

lean sandal