Why does my sprite change direction when there's a slope?

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

I was trying to implement the RayCast2D node to detect collisions, in order to avoid ledges. The sprite would change its direction once it detects a ledge.

My code:

    extends KinematicBody2D

const GRAVITY=20
var SPEED=50
var motion=Vector2()
const UP=Vector2(0,-1)
var flag=1
func _physics_process(delta):
	motion.y+=GRAVITY
	
	if is_on_wall() :
		$RayCast2D.position.x*=-1
		SPEED*=-1
		
	if $RayCast2D.is_colliding()==false:
		SPEED*=-1
		#print('not detected')
		$RayCast2D.position.x*=-1
		flag=0
	else:
		SPEED*=1
		#print('detected')
		$RayCast2D.position.x*=1
		flag=1
	if SPEED<0 or flag==0:
		$Sprite.flip_h=true
	else:
		$Sprite.flip_h=false
		
	print(SPEED)
	motion.x=SPEED
	$Sprite.play("walk")
	motion=move_and_slide(motion,UP)
	pass

The code works fine, as the sprite can detect ledges and avoid them. But when it gets to an upward slope, the sprite changes its direction again after climbing half of it. It doesn’t make any sense, as the SPEEDwon’t change as long as it doesn’t detect a ledge. Is there something wrong with the code?