+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

asked Dec 20, 2016 in Engine by ismaelgame7 (143 points)

2 Answers

+6 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);

answered Dec 20, 2016 by kubecz3k (1,253 points)
edited Dec 20, 2016 by kubecz3k

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

+8 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.

answered Dec 20, 2016 by Warlaan (1,114 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.