0 votes

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?

asked Jun 8 in Engine by Godot_Starter (265 points)
edited Jun 8 by Godot_Starter

1 Answer

0 votes
Best answer

Take both characters global_position -> measure distance between 2 points(using Pythagoras or the Vector2.distancetopoint)

answered Jun 8 by rustyStriker (1,073 points)
selected Jun 8 by Godot_Starter

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

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
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.