How to make my platform change direction when hitiing a collusional shape

Godot Version

4.2.2

Question

extends CharacterBody2D

var speed = 100
var direction = 1
var overlapping_bodies = get

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

if is_on_wall():
	direction *= -1


move_and_slide()

is only going right and when hitting the collision shape just keep hitiing it

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()

whats this code because its giving me an error

wait i fix it but is still doing the same thing

have you tried maybe changing “ui_right” and “ui_left” with your actual input keys?

Yes i tried it and nothing happen

Move move_and_slide before the is_on_wall check:

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

	move_and_slide()

	if is_on_wall():
		direction *= -1
1 Like

thank you

but why is it working when move_and_slide() is before if is on wall()

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 direction again, which means that in the fourth frame it will move to the right and touch the wall again, resulting in an endless loop.

1 Like