A different solution using math

(0,0) on our ships, rockets, etc, is the middle. (0,0) plus half its width gets us the trailing edge of the sprite.

The following code uses that fact to remove the ship as soon as its whole body is off the left edge of the screen.

extends Area2D

# Variables to control speed & sine wave of ship
# Todo: Add a check to see if ship is in top half or bottom half of screen,
# and change the initial wave direction based on that, to keep them on screen.
@export var speed : float = 250
@export var frequency : float = 0
@export var amplitude : float = 15

# Get the image of the enemy
@onready var sprite = get_node("Sprite2D")

# A changing number we can get the cosine of
var time : float

func _process(delta) -> void:
	time += delta

func _physics_process(delta):
	# Move the ship left. 
	# Todo: add controls to make ship fly loops
	global_position.x = global_position.x - (speed * delta)
	# Move the ship along the Y to fly in a sine wave
	global_position.y += get_sine()
	# Get viewport & Sprite2D rects
	var viewport = get_viewport_rect()
	var spriteRect = sprite.get_rect()
	# Set the offscreen point on the trailing edge of the ship
	var offscreenMarker = global_position.x + (spriteRect.size.x/2)
	# If that point is offscreen so is the rest of the ship; destroy self.
	if(offscreenMarker < viewport.position.x):
		queue_free()

# Trig.
func get_sine():
	return sin(time * frequency) * amplitude

Enjoy!

3 Likes

I was literally about to do this same thing on my enemies. Thanks for a great suggestion!

The one part in the code posted here I couldnt find on Godot 4 was the spriteRect.size and i found that you can do the same thing by typing in spriteRect.texture.get_size(). Im not sure if this was changed or what not but I figured that I would post about that here for anyone else that has ran into this change.

Thanks!

1 Like

Privacy & Terms