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?

in Engine by (320 points)
edited by

1 Answer

0 votes
Best answer

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

by (1,183 points)
selected by

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.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.