Enemy movement(right and left)

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

I’ve used this:

extends KinematicBody2D

const GRAVITY = 10
const SPEED = 60
const FLOOR = Vector2(0, -1)

var velocity = Vector2()

var direction = 1

func _ready():
pass

func _physics_process(delta):
velocity.x = SPEED * direction

if direction == 1:
	$AnimatedSprite.flip_h = true
else:
	$AnimatedSprite.flip_h = false
$AnimatedSprite.play("walk")

velocity.y += GRAVITY

velocity = move_and_slide(velocity, FLOOR)

if is_on_wall():

	direction = direction * -1
	$RayCast2D.position.x *= -1

if $RayCast2D.is_colliding() == false:

	direction = direction * -1
	$RayCast2D.position.x *= -1

But when the enemy collides with a wall or goes to an edge he starts changing direction super fast on himself without walking. I used a raycast that doesn’t touch the collision shape and it’s directed on the ground (x=0 y=32)

:bust_in_silhouette: Reply From: Becbunzen

This part seems to do it:

if is_on_wall():
     direction = direction * -1

If you overlap so this is triggered, direction changes, but then it does not move away fast enough, so still overlaps for next frame.