"Flickering" in sprite when enemy is moving during roam

Godot Version



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

func roam():
	if !chasing:
		var rng = RandomNumberGenerator.new()
		var direction = Vector2.ZERO
		if roam_timer_timeout:
			roaming = true
		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.

At very small distance values, direction_to will become less accurate due to floating-point precision issues.

You can avoid this by skipping/disabling roaming activity when distance_to is below a threshold.

1 Like

We looked a bit into it, and using is_equal_approx() we managed to remove the flickering with your advice, thank you so much!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.