Collision Problems Godot4

Godot Version



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():
func _physics_process(delta):
	var dir_to_player = global_position.direction_to(player.global_position)
	velocity = dir_to_player * move_speed

func take_damage():
	health = health - Global.daño
	await get_tree().create_timer(0.1).timeout
	if health <= 0:

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

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:

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

And then this:

func _on_navigation_agent_2d_velocity_computed(safe_velocity):
	velocity = safe_velocity
    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


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

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