Make KinematicBody2D objects collide

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By gerep

Hi,

I’m working on a top-down shooter.

The mobs are KinematicBody2D objects that I am spawning. It is not a problem if I have to change the type.

They are following the player and eventually they will get on top of each other.

I want to avoid it. Looking around I found examples I can use to make them bounce but that’s not what I want, I don’t want them to take the same space.

Thank you.

:bust_in_silhouette: Reply From: Gluon

Well as long as you have collision shapes on your enemies and you make sure those collision shapes are looking at the same layer the enemy is on then they will bump into each other rather than go on top of each other.

Thank’s what I was expecting but I am missing something I can’t find.

You see that the Mob (kinematicbody2d) has the collision layer and mask set to 1 (default).

The Area2D I am using to detect when a bullet hits it.

The CollisionShape2D is also using the default configuration.

In the Level scene I am spawning the mob like this:

extends Node2D

var mob: PackedScene = preload("res://scenes/Mob.tscn")
var spawn_time = 0

func _ready():
    spawn_time = randi() % 5 + 1

func _process(delta):
spawn_time -= delta

if spawn_time <= 0:
	spawn()
	spawn_time = randi() % 5 + 1

func spawn():
    var m = mob.instance()
    m.position = Vector2(randi() % 1024, randi() % 600)
    add_child(m)

enter image description here

gerep | 2022-12-27 20:38

On the collision shape in visibility is the collision shape also set to layer 1?

Gluon | 2022-12-28 21:16

:bust_in_silhouette: Reply From: gerep

The problem was in my mob script. I was only changing its position and not checking for collisions.

Before:

func _physics_process(delta):
	position = position.move_toward(player.position, speed * delta)	
	look_at(player.position)

After:

func _physics_process(delta):
	position = position.move_toward(player.position, speed * delta)	
	look_at(player.position)
	move_and_collide(Vector2.ZERO)

I don’t know if using Vector.Zero is the best or correct thing to do.