Try using this code I added some comments so you understand what im tryna do
extends CharacterBody2D
var speed = 100 # Movement speed in pixels per second
var move_direction = Vector2.RIGHT # Initial movement direction (can be changed)
func _physics_process(delta):
# Get input for horizontal movement (modify for your input system)
var horizontal_movement = Input.get_action_strength(“ui_right”) - Input.get_action_strength(“ui_left”)
# Update move direction based on input
if horizontal_movement > 0:
move_direction = Vector2.RIGHT
elif horizontal_movement < 0:
move_direction = Vector2.LEFT
# Apply movement using velocity
velocity = move_direction * speed
# Handle wall collisions (assuming is_on_wall() checks for walls)
if is_on_wall():
# Reflect velocity on the x-axis to change direction
velocity.x = -velocity.x
move_and_slide()
In your original version, you do things in this order:
compute velocity (as the product of speed and direction)
check if currently on a wall (note: you haven’t yet moved)
move (based on the velocity you computed before)
If you step through this process for 4 frames in a row, you’ll notice that if the first call to move_and_slide ended up on a wall, in the second frame you still compute the velocity as before (i.e. with the old direction value) and only then flip the sign of direction, so you’ll still move to the right. Which means that your character remains on the wall for frame 3 as well and while this time it will move away from the wall (because the direction was flipped) you’ll then flip the sign of directionagain, which means that in the fourth frame it will move to the right and touch the wall again, resulting in an endless loop.