Making enemies move

Ive already created a spawning system in my sidescrolling 2d game and I have 2 enemies I want to move.

Bat: I want it to go down from the top of the screen slowly by making it go down and fly up a bit before going down again over and over again. This is a rigid body 2d.

Spike: I just want it to move left across the screen. This is also a rigid body 2d.

P.S: A way to despawn them after a while would also be nice.

You can despawn them with queue_free(), so you can either hook up a timer, or do something like:


const LIFETIME: float = 20.0 # 20 seconds...
var life: float

func _ready() -> void:
    life = 0.0

func _process(delta: float) -> void:
    life += delta
    if life >= LIFETIME:
        queue_free()

For movement, it depends on whether you want to use move_and_slide() or move them by hand; if you want to move them by hand, it might look something like:

# spike

const VELOCITY: float = -100.0 # 100 pixels per second

func _process(delta: float) -> void:
    position.x += (delta * VELOCITY)
# bat

const DOWN_TIME:  float =  2.0 # 2 seconds
const DOWN_SPEED: float = 32.0 # 32 pixels
const UP_TIME:    float =  1.0 # 1 second
const UP_SPEED:   float = -8.0 # 8 pixels, up

var going_down:   bool  = true
var travel_time:  float = 0.0

func _process(delta: float) -> void:
    travel_time += delta
    if going_down:
        position.y += (DOWN_SPEED * delta)
        if travel_time > DOWN_TIME:
            travel_time = 0.0
            going_down  = false
    else:
        position.y += (UP_SPEED * delta)
        if travel_time > UP_TIME:
            travel_time = 0.0
            going_down = true

Doing the same thing with move_and_slide() is similar, it just specifies a velocity instead of manually frobbing position.

2 Likes