Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | da_dev |
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)
print("if")
if (bullets > 0 && canFire):
auto_fire()
else:
rotation = trans.angle() + deg2rad(90)#
print("else")
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?
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:
- Area2D should be used to detect objects entering/exiting
while
loops should be avoided as they block game processing. Your code needs to run once per frame, don’t block the game loop.- Your distance calculations could be much simpler. Read up on how vectors work, and see
Vector2.length()
: Vector math — Godot Engine (latest) documentation in English
kidscancode | 2019-06-12 16:01
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)
da_dev | 2019-06-12 16:59