RayCast2D don't work

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

I tried using RayCast2D to make the enemy walk in the platform without falling, but it don’t works, he stay idle and the sprite don’t stop flipping. (And it’s enable in property editor)

This is the link for you can download my project: Jogo da merda – Google Drive

This is the script of the enemy:

extends KinematicBody2D

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

var velocity = Vector2()

var direction = 1

func _ready():
pass

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

if direction == 1:
$AnimatedSprite.fliph = false
else:
$AnimatedSprite.fliph = true

$AnimatedSprite.play(“walk”)

velocity.y += GRAVITY

if isonwall():
direction = direction * -1
$RayCast2D.position.x *= -1

if $RayCast2D.is_colliding() == false:
direction = direction * -1
$RayCast2D.position.x *= -1

velocity = moveandslide(velocity, FLOOR)

:bust_in_silhouette: Reply From: 2D

I looked at your project and I found two issues:

  1. The Raycast2D is never colliding because in your test_area tilemap, you need to enable collision layer 1 b/c your raycast is using mask 1. This will get the enemy to start moving left to the ledge and turn okay.
  2. When the enemy hits the wall, it will be stuck there, flipping indefinitely. One way to fix this is to add a short delay between the next wall check. You can add a timer node to your enemy with a 0.5 s time and a flag that gets checked before flipping the direction.

I updated your enemy code:

extends KinematicBody2D

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

var velocity = Vector2()

var direction = 1
var wall_wait = false

func _ready():
	pass


func _physics_process(delta):
	velocity.x = SPEED * direction
	velocity.y += GRAVITY
	
	if direction == 1:
		$AnimatedSprite.flip_h = false
	else:
		$AnimatedSprite.flip_h = true

	$AnimatedSprite.play("")

	if is_on_wall() and !wall_wait:
		direction = direction * -1
		$RayCast2D.position.x *= -1
		wall_wait = true
		$Timer.start()

	if $RayCast2D.is_colliding() == false:
		direction = direction * -1
		$RayCast2D.position.x *= -1

	velocity = move_and_slide(velocity, Vector2.UP)

func _on_Timer_timeout():
	wall_wait = false

I also made these changes and re-shared the project with you on google docs.