Get the distance between 2 KinematicBody2ds

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Godot_Starter

How can I get the distance between 2 KinematicBody2ds (Here A and B)?

For example in the Script of KinematicBody2d A I have a variable var BodyB = get_parent().get_node(BodyB) which is the other body and a variable var distance_to_BodyB which have to be set to the distance between body A and B in pixels as a number. How can I do that?

:bust_in_silhouette: Reply From: rustyStriker

Take both characters global_position → measure distance between 2 points(using Pythagoras or the Vector2.distance_to_point)

Can you maybe make a code example which solves the problem in the example? Because I am a beginner and don’t know how I can do what you sad in practice

Godot_Starter | 2020-06-08 14:43

Ok, the more fun way(Mathematical way :D)

 X² + Y² = D²

In other words

DeltaX² + DeltaY² = Distance²

So! Delta means X1 - X2(or X2 - X1) but we are squaring it so it wont matter.

we have body A → A and body B → B and each has a position property so we will do this

 var distance = pow(A.position.X - B.position.X,2) + pow(A.position.Y - B.position.Y,2);
 distance = sqrt(distance) # Since X² + Y² = Distance² we need to square root it

rustyStriker | 2020-06-08 15:53