+3 votes

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? :D

in Engine by (145 points)

2 Answers

+8 votes

Assuming you are working with 2d:

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

by (1,279 points)
edited by

Okay thank you, This will help me a lot.

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).

+1 from me @eons

+9 votes

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.

by (1,116 points)
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.