Collision Problems Godot4

Godot Version

4

Question

I have this code for Godot 4. The problem is that when the enemies collide with each other, I want them to surround the player, but instead, the enemies bunch up in a horizontal line, which is not what I want. Here’s my code:

extends CharacterBody2D

var health = 100
var blood = preload("res://scenes/blood.tscn")
var move_speed = 150

@onready var player : CharacterBody2D = get_tree().get_first_node_in_group("player")



func _ready():
	$Enemie1.play("idle")
	
func _physics_process(delta):
	var dir_to_player = global_position.direction_to(player.global_position)
	velocity = dir_to_player * move_speed
	move_and_slide()


func take_damage():
	health = health - Global.daño
	$Enemie1.play("damage")
	await get_tree().create_timer(0.1).timeout
	$Enemie1.play("idle")
	if health <= 0:
		print(self.position)
		bloodInstance()
		queue_free()

func bloodInstance():
	var blood_instance = blood.instantiate()
	blood_instance.position = self.position
	get_tree().root.add_child(blood_instance)

So, your game is 2d top-down, right?

In this case you might want to add avoidance to your enemies

You’ll need to add navigation agent 2d for your enemy and make navmesh with navigation region 2d

Here’s full documentation → Navigation

You need to add velocity computed to your script:
image

Then add this code to work with it

@onready var nav = $your_navigation_agent

var direction = Vector2()


func _physics_process(_delta):
	direction = nav.get_next_path_position() - global_position
	direction = direction.normalized()
	var intended_velocity = direction * move_speed
	nav.set_velocity(intended_velocity)

And then this:

func _on_navigation_agent_2d_velocity_computed(safe_velocity):
	velocity = safe_velocity
	move_and_slide()
    nav.target_position = player.global_position

In this way your enemies not only will avoid each other, they also will walk only where your navmesh is, so they won’t stuck in walls, etc.

There might be others way to do it, but there is one of them

2 Likes

ty for reply ^^ I tried but the problem persists, I tried adding a collision repellent and it works (sort of) but I think it’s finally resolved for the moment ahahah