Godot Version
4.2.1
Question
Hi! Me and a couple of friends are quite new at making games, and we’ve encountered an issue trying to make a random “roaming” function for our enemies.
We wanted the enemy to roam around a given area that’s calculated when the enemy spawns. If the enemy isn’t chasing the player, it roams around randomly within the given area, and if it gets bored of chasing the player, it returns to its original given area if it went outside of it during the chase. Both of these mechanics work, but, the enemy flickers.
The print function returns to us that once the enemy reached its “target position”, its direction constantly switches from positive to negatives or vice versa, which causes it to go left to right or up and down every single frame. This bug also sometimes happens when it moves diagonally.
This is the code:
func update_target_position():
var target_vector = Vector2(randi_range(-roam_range, roam_range), randi_range(-roam_range, roam_range))
roam_target_pos = start_pos + target_vector
print(roam_target_pos)
func roam():
if !chasing:
var rng = RandomNumberGenerator.new()
var direction = Vector2.ZERO
if roam_timer_timeout:
roaming = true
start_roam_timer(rng.randf_range(3,6))
direction = round(round(global_position).direction_to(round(roam_target_pos)))
print_debug("direction: ", direction)
print("gp: ",round(global_position))
print("rtp: ",roam_target_pos)
if round(global_position) == roam_target_pos:
roaming = false
velocity = direction * speed if (direction != Vector2.ZERO) else Vector2.ZERO
(the roam() function gets updated every frame).
What could cause the bug? Is there a better way to do this? Thank you in advance for the help.