Coding an area2D node going up an down within the limits of the level ?

Godot Version

Godot 4.4.1-stable.official [49a5bc7b6]

Question

Hello everyone,

I am very new in coding and in Godot. My 2D game project makes good progress thanks to all the tutorials and help one can find around.

I cannot manage to code an ennemy which behavior would be basic vertical move up and down within the limits of the level.

I’d like to avoid usind path2D since the initial spawn position will be random. I’d also like to avoid using colisions and signal to define the behavior (to keep the level “clean”).

Let’s assume that the ennemy moves with such a code :

extends Area2D
var direction = Vector2(0,1)
var rndx = randi_range(0,500)
var	rndy = randi_range(0,500)
var speed = 100

func _ready() -> void:
	position = Vector2(rndx, rndy)

func _process(delta: float) -> void:
	position += direction * speed * delta

Would there be an easy way to code for “once position.y reaches 800 or above, then direction=Vector2(0,-1). One position.y reaches 0 or below, then direction=Vetor2(0,1)” ?

I do not manage to code this with if statements only.

Thanks a lot for your help !

Hi,

Absolutely, you can do something like this:

position += direction * speed * delta

if position.y >= 800:
    direction.y = -1
elif position.y <= 0:
    direction.y = 1

I did not try the code, but it should work fine.

1 Like

Thank you very much,

it works indeed. I thought I tried a so,ewhat similar solution which did not work… My syntax must have been wrong !

Thanks again !

1 Like