Change the direction of a platform enemy

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

Hi guys,
I’m doing a platform game and i have a problem with the enemies, i want that after they reach the end of the platform they change direction. how can i do it?
Thanks in advance for the help

:bust_in_silhouette: Reply From: njamster

On either side of your enemy character (left and right) attach a RayCast2D-node pointing downwards. Then after each of their moves check if they still collide (with the platform). If not, change the direction the enemy is moving:

extends KinematicBody2D

var direction = Vector2.RIGHT
const SPEED = 100

func _physics_process(delta):
	move_and_collide(direction * SPEED * delta)
	if not $RayCastLeft.get_collider():
		direction = Vector2.RIGHT
	if not $RayCastRight.get_collider():
		direction = Vector2.LEFT