How to move "Enemy" (KinematicBody2D) towards player (KinematicBody2D) using move_toward() but still using collisions

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

So, I have two KinematicBody2D nodes, the Player, and the enemy. I want the enemy to be able to move towards the player, but with the way that I’m doing it (move_toward()), the enemy completely ignores the StaticBody2D nodes (walls / ground) and just goes right through them. My code is below (Sorry about indents, I’m new to the Q&A and don’t know how to correctly do them):
extends KinematicBody2D

var motion = Vector2()
var player

func _enter_tree(): player = get_node("/root/Level1/Player")

func _physics_process(_delta):
look_at(player.position)
position.x += move_toward(position.x, player.position.x, player.speed)
position.y += move_toward(position.y, player.position.y, player.speed)

:bust_in_silhouette: Reply From: Millard

Maybe the move toward function ignores physics? (not sure). Try the kinematic move and slide function.

be aware that the enemy won’t navigate around the collisions, he will just hopefully not go through them.

hope it helps. :slight_smile:

:bust_in_silhouette: Reply From: whiteshampoo

If you want to use physics (collisions, etc) you cannot just set the position.
You have to use smothing like move_and_slide or move_and_collide.

As a very very very dirty fix, i think it would work if you add move_and_slide(Vector2.ZERO) at the end. (untested!)