Godot Version
Godot 4.4
Hey guys! Just wanted to ask, in a 2D platformer, how do I make it so that an enemy character moves back and forth at all times, such as the enemy moves to the left by default, then when they hit a wall, they flip around and go to the right, and then when they hit a wall, they flip around and go back to the left, and so on, so forth.
Here’s the enemy character here:
I already have the Enemy with a CharacterBody2D node, an AnimatedSprite2D node (That only has its walking animation), a CollisionShape2D node (with a RectangleShape2D chosen for the enemy, and is at the tiny collision shape at the bottom of the enemy), an Area2D node (with a CollisionShape2D nodee, with a RectangleShape2D chosen for the enemy, and covers the entire enemy), two RayCast2D nodes (One called “LeftRay”, which is at the bottom left pointing downwards, and the other called “RightRay”, which is at the bottom right pointing downwards.), and two more RayCast2D nodes (One called “LeftWallRay”, which is pointing to the left, and the other called “RightWallRay”, which is pointing to the right, and these two raycasts are which I presume to have the enemy be detected whether it’s hitting a wall on each side.)
Here’s the GDScript code for the enemy:
extends CharacterBody2D
@onready var player_node: CharacterBody2D = get_parent().get_node(“Player”)
var speed: float = 35.0
var gravity = 15
@export_range(-1, 1) var dir: int = 1
func _ready() → void:
if dir == 0:
dir = 1
$AnimatedSprite2D.flip_h = false if dir == 1 else true
func _physics_process(delta: float) → void:
if dir == 1 and (!$RightRay.is_colliding() or $RightWallRay.is_colliding()):
$AnimatedSprite2D.flip_h = true
dir = 0
_wait_dir_change(-1)
if dir == -1 and (!$LeftRay.is_colliding() or $LeftWallRay.is_colliding()):
$AnimatedSprite2D.flip_h = false
dir = 1
velocity.x = lerp(velocity.x, dir * speed, 10.0*delta)
velocity.y += gravity
move_and_slide()
func _wait_dir_change(desired_dir: int):
await get_tree().create_timer(0.5).timeout
dir = desired_dir
func _on_area_2d_body_entered(body: Node2D) → void:
if body == player_node:
get_tree().call_deferred(“reload_current_scene”)
I already implemented this into GDScript, and when I went to test it out, i can’t really describe it well, but it was stuck to the right side of the wall and wasn’t moving, or it was moving back and forth, but not flipping in the proper direction and the enemy was too low to the ground.
Can you guys help me? Thanks for giving advice and helping me if you do!!!


