how to check distance of an object?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ismaelgame7
:warning: Old Version Published before Godot 3 was released.

Hello,

How do I check the distance of my player to an enemy?
And when the player gets close to the enemy, The enemy starts throwing something?

Sorry my english is not so good
Can someone help me, please? :smiley:

:bust_in_silhouette: Reply From: kubecz3k

Assuming you are working with 2d:

var distance2Hero = enemy.get_global_pos().distance_to(hero.get_global_pos()); if(distance2Hero<100): enemy.throwBulletAt(hero);

Okay thank you, This will help me a lot.

ismaelgame7 | 2016-12-20 16:49

You can also get more basic math in the docs:
http://docs.godotengine.org/en/stable/tutorials/vector_math.html

And may be better to put the distance detection in the object that is going to react to it (but that depends on the design, of course).

eons | 2016-12-20 17:04

+1 from me @eons

kubecz3k | 2016-12-20 17:28

:bust_in_silhouette: Reply From: Warlaan

If you want something to happen when the player gets within a certain distance from an object attach an area to the player and connect the body_enter-signal. That way you don’t need to check the distance every frame. The physics engine is much better at checking distances than such a check in a script.