Godot Version
Godot 4.3
Question
Hello, we are creating a 2d godot game in which we need enemies to appear randomly all over the map.
So far we have an enemy that chases you if you enter a 2d area, the player and the map.
Our problem is that when the enemy appears randomly, even though the player is within its area of vision, it does not chase the player and instead, it moves away.
Also, it gives the impression that the spawner moves with the player and does not stay still despite not being a child node.
We appreciate your help with this project
Can you share some code and maybe your scene setup?
1 Like
Of course
, I attach here a document with the code of our enemy (zombie), the code of our spawner, the code of our player, an image of the player within the field of vision of our enemy and an image of the error that happens with the spawner (we have hidden the area of vision of the enemy so that it can be seen better).
Thanks for your help
[Document]
https://docs.google.com/document/d/1Co4Bwi81cXrlV_gQp9UKHXrqZTndgGTF/edit?usp=sharing&ouid=100387705591224252432&rtpof=true&sd=true
Sorry for the previous document, I didn’t give access to it, it’s updated now 
Hi!
We still need to ask access for the file.
You can paste code (between ~~~ for it to be formated) here or screenshots directly. It will help!
2 thoughts though :
- It might be a problem of collision layers and masks. You can start by having a look at that.
- To debug, try to print something to console when something enters the area2D.
Cheers!
2 Likes
enemy script:
extends CharacterBody2D
var player
var speed = 150
var vidas = 3
var hit = true
@onready var animation = $AnimatedSprite2D
func _process(delta: float) → void:
follow()
func follow():
if player != null:
velocity = position.direction_to(player.position) * speed
if velocity.x > 0:
$AnimatedSprite2D.flip_h = true
animation.play("lados")
if velocity.x < 0:
$AnimatedSprite2D.flip_h = false
animation.play("lados")
move_and_slide()
func _on_follow_body_entered(body) → void:
player = get_tree().get_nodes_in_group(“player”)[0]
func _on_follow_body_exited(body) → void:
player = null
Since I’m a new user, it won’t let me send multiple photos, so I have to send you our compressed project. I’ve attached a link here to download it from MEGA.
I hope it helps you solve my problem
I appreciate your help.
I see the pasted code snippet is using position rather than global_position.
Any time you want to have one node target and chase another, the easiest way to calculate the direction is by using the global_position of both nodes.
1 Like