Problems with getting an enemy to follow the player
Asked Answered
N

1

0

[Pictures below to picture the problem]

Hi all!!

I'm trying to make a top down game where there are zombies who chase the player. I'm new to Godot and everything was fine until I had to make the enemies follow the player.

In fact, that was easy with this code (it is in the main scene where the enemies are instantiated):

func move_enemy():
	var enemy = get_tree().get_nodes_in_group("Enemy")
	
	for i in range(0, enemy.size()):
		
		
		enemy[i].velocity = ($Player.position - enemy[i].position).normalized() * speed
		enemy[i].look_at($Player.global_position)
                enemy[i].set_nav() #explained later
		enemy[i].get_next() #explained later
		enemiy[i].move_and_slide()

This was working fine but the enemies didn't dodge walls and obstacles, so I tried the navigation path system.

In the enemy scene I put a NavigationAgent2D node and this code:

func set_nav():
	var player = get_tree().get_nodes_in_group("Player")
	
	$nav.target_position = player[0].global_position
	
	
func get_next():
	$nav.get_next_path_position()

In the map scene I have a NavigationRegion2D

This is just not working. The enemies chase the player but don't follow the paths. Images to explain.

In first image you can se the navigation polygon. The enmies Spawn at the top left marker.

In second image you can see that even where there is a path to follow, the enemy don't follow it and goes straight to the wall.

Path desired distance is 10
Target desired distance is 10
Path Max distance is 10.

Thank you for your time!

Navarre answered 9/11, 2023 at 13:39 Comment(0)
N
1

Ok, I solved it.

I changed the movement script to this:

func mover_enemigo():
	var enemigo = get_tree().get_nodes_in_group("Enemigo")
	
	for i in range(0, enemigo.size()):
		enemigo[i].set_nav()
		var next_point = enemigo[i].get_next()
		enemigo[i].velocity = (next_point - enemigo[i].position).normalized() * speed
		
		enemigo[i].look_at($Player.global_position)
		
		enemigo[i].move_and_slide()

Now the enemy follow the path because the velocity vector points to the next point in the path

Navarre answered 9/11, 2023 at 14:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.