Why does this not work

Godot Version

Godot 4

Question

its an enemie script btw
it just doesnt move

extends AnimatedSprite2D

var speed = 50
var direction = 1
func _ready():

self.position.x = 200

self.position.x += direction * speed * get_process_delta_time()

if direction == 1 and self.position.x >= 200:
direction = -1 # Change direction to move left
elif direction == -1 and self.position.x <= -200:
direction = 1 # Change direction to move right

You have all your position/direction changes inside the ready function.

Try moving it into the _process() function.

can you write the script with it?

Like this?

doesnt work

You’re setting the position.x to 200 every frame this script runs, so your sprite will appear like it doesn’t move.

Try something like this:

extends AnimatedSprite2D

var speed = 50
var direction = 1

func _ready():
	self.position.x = 200 #Setting the x position on ready.


func _process(delta: float):

	self.position.x += direction * speed * delta

	if direction == 1 and self.position.x >= 200:
		direction = -1 # Change direction to move left
	elif direction == -1 and self.position.x <= 100: #I've changed this to 100 so it stays within the viewport in my example. this will depend on how your scene is set up.
		direction = 1 # Change direction to move right
1 Like

Thank you.

It works thank you SO MUCH!

1 Like