Here’s a simple way to do it (assuming your enemy only moves from left to right)
extends Area2D
var direction = 1
var start_position = 0
var walking_distance = 50
var speed = 20
func _ready():
start_position = position.x
func _physics_process(delta):
position.x += direction * speed * delta
if (position.x >= start_position + walking_distance):
direction = -1
if (position.x <= start_position - walking_distance):
direction = 1
On the other hand, Brackey’s tutorial explains this with a bit more detail and also adds simple raycasting to check if the enemy has hit a wall (in that case it will also change direction). In minute 42 he explains how to make an enemy roughly like the one you described.
Hi, I read your question again. My solution is based on length of the walk. You still want to do it by time?
If so here’s how to simply do it by code, the enemy changes direction every 2 seconds:
extends Area2D
var direction = 1
var speed = 20
var walk_length = 2000 #in milliseconds
var last_turn = 0
func _ready():
last_turn = Time.get_ticks_msec()
func _physics_process(delta):
position.x += direction * speed * delta
var current_time = Time.get_ticks_msec()
if (current_time - last_turn > walk_length):
last_turn = current_time
direction *= -1