The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates. | Twitter

0 votes

So, I have a KinematicBody2D as a player's soldier, and another one as an enemy. I have all nodes of every single friendly soldier and every single enemy stored in two global arrays.
I want to have a soldier, which upon entering a "detection radius" would start firing at the enemy sprite. I tried this:

#   Spotting an enemy and firing
for i in gv.enemies: #gv is global variables
    var enemy = i
    if (position.x - i.position.x) * (position.x - i.position.x) + (position.y - i.position.y) * (position.y - i.position.y) < detection_radius * detection_radius: #if soldier is in range of any of the enemies
        while (position.x - enemy.position.x) * (position.x - enemy.position.x) + (position.y - enemy.position.y) * (position.y - enemy.position.y) < detection_radius * detection_radius: #if soldier is still in range of the enemy
            var enemy_angle = enemy.position - self.position 
            rotation = enemy_angle.angle() + deg2rad(90)
            if (bullets > 0 && canFire):
        rotation = trans.angle() + deg2rad(90)#

Surprisingly, when I run this code, game lags at the start and doesn't begin. I've noticed that's something with the "while" block.

Anybody has idea how to solve this?

in Engine by (32 points)

There are many, many things wrong with this code and your approach. I highly suggest reading through the Godot docs, especially the "Step by step" section, to learn how Godot works. Do the tutorial game in that section.

Some suggestions:
1) Area2D should be used to detect objects entering/exiting
2) while loops should be avoided as they block game processing. Your code needs to run once per frame, don't block the game loop.
3) Your distance calculations could be much simpler. Read up on how vectors work, and see Vector2.length():

Thank you! I really have to be more patient when reading Godot docs (I really want to create fancy stuff before I learn the basics)

Please log in or register to answer this question.

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 Frequently asked questions and 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 [email protected] with your username.