#How to move a entity towards another entity?
1 messages · Page 1 of 1 (latest)
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
Thank you!
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.
That's true. I usually define a distance treshold when moving completely towards a target. If I am closer than that I just place the object immediately at the target.