How to make the enemy follow the player only on x axis

Hello again :o I’m a complete beginner using Godot 4 to create a 2D platformer game for my school project. I’ve looked for other posts but it wasn’t really clear for me.

I wonder how I can make the enemy follow my player only on the x axis. I’ve tried to ask AI even though it’s not that advanced yet. But its script didn’t work since the enemy didn’t move at all and stayed at the same exact spot. Here is the script:
The script
Thank you if you can help c:!

So, first if the enemies and player have a common parent pass the reference to the enemies via the parent. Or you can put player in a group and use the group to find player.

So, all you should have to do is

var dir = (player.global_position - global_position).normalized()
velocity.x = dir * SPEED
move_and_slide()

I noticed your enemies were rigid bodies, if you need them to be rigid bodies that code won’t work, if they are characterbody2d it should work.

Since you are complete beginner, if you node structure is like this

NodeWorld
Player as child
Enemy as child

Then in NodeWorld in _ready call $Enemy.player = $Player

In Enemy you’ll have a var player.

Now, if you have multiple enemies, it might be easier in the player _ready() to

add_to_group(“player”).

Then, in your enemy script you can have a var that is

var player = get_tree().get_nodes_in_group(“player”)[0]

Could you only apply the .x of your vectors?

linear_velocity.x = direction.x * speed

Make sure to paste scripts instead of screenshots

I see:o here is the initial script:

extends RigidBody2D

@export var speed = 200.0  # Speed of the enemy's movement
@onready var player = get_node_or_null("furet prox max")  # Relative path to the player (adjust based on your scene)

func _physics_process(delta):
    if player:
        # Check positions
        print("Player position:", player.global_position, " | Enemy position:", global_position)

        # Calculate the direction
        var direction = (player.global_position - global_position).normalized()
        print("Direction:", direction)

        # Apply speed by updating `linear_velocity`
        linear_velocity = direction * speed
    else:
        print("Error: Player not found. Check the node path.")

Sorry for bothering, I’m a bit lost about where to instert the code you just gave.

So, with my script you’d need to change the node type to a CharacterBody2D, at the moment your script is for a RigidBody2D.

If you need it to be a RigidBody, try the other suggestion by @gertkeno, otherwise change node type, and put my script in the physics_process and delete the rest that is there.