# Enemy movement controll!

I’m facing a big wall right now

It’s about how to move the enemy

I want the enemy to change direction after a certain period of time, but I don’t know how to do it…

Plus, I want to know how to move at the speed I want, only a certain distance I want!

This is the code I’ve found so far!
Could you help me…?

Hi.

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

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.

1 Like

Waaaa!!!
Thank you, thank you so much for your sweet and awesome solution!!!
It’s perfect!!!
Thank you again!!

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

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

``````

Good luck!

1 Like

Ahhhh I totally forgot the time…!
Thank you so much for taking the time to answer back as part of it!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.