Only the first instance of a spawned enemy follows code instead of all of them (and a small question about enemy pathfinding)

I’m developing a 2d platformer in version 4.2.1 for a game jam and I have coded the enemy’s behaviour as follows:

extends CharacterBody2D

@onready var player = get_node("/root/Game/Player")
@onready var enemy = get_node("/root/Game/Enemy")

var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
var jump_speed = -600.0
var speed = 250.0
var health = 100.0

func jump_after_player():
	if (enemy.get_global_position().y - player.get_global_position().y) > 180 and is_on_floor():
		velocity.y = jump_speed

func _physics_process(delta):
# Add the gravity.
	velocity.y += gravity * delta
	var direction = global_position.direction_to(player.global_position)
	velocity.x = direction.x * speed
	jump_after_player()
	move_and_slide()

Testing the code with a single instance of an enemy worked well enough, but after adding coding for enemy spawns in the game script, there was a single thing that I realized only the first instance of enemies would do.

func jump_after_player():
	if (enemy.get_global_position().y - player.get_global_position().y) > 180 and is_on_floor():
		velocity.y = jump_speed

The jumping. And my only guess is that, since it’s named “enemy.get_global_position().y” it only applies to the first instance of the enemy since that’s the one that is technically called enemy while the others are enemy2, enemy3, enemy4, etc and that’s why it doesn’t work with those.

Is my reasoning correct? Either way, how do I go about fixing this?

And my other small question about enemy pathfinding is the line of code I use to make the enemies follow after me:

var direction = global_position.direction_to(player.global_position)
velocity.x = direction.x * speed

This works… but the movement feels unnatural, I made it so enemies can pass through the player but when they do they stay in place of the player (of course, given how that line code works) and when you move away they separate from you veeery slowly (cuz i made them slower than the player). I don’t have a way to record that gameplay right now so sorry if my description of the situation isn’t enough. But the point is, is there a way to make that horizontal movement following the player more natural?

Yes. you are getting the first node called Enemy here @onready var enemy = get_node("/root/Game/Enemy") so only the first one will work.

Just change the if condition to if global_position.y - player.global_position.y > 180 and is_on_floor():

1 Like

lol yeah that was exactly it, goofy mistake to do all that calling inside the script that i want to call, thanks for pointing it out

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