How to do a boomerang type weapon

Godot Version

4.3

Question

Hello, I am starting with game development and I am working on my first game. Something like vampire survivors. I am trying to program a weapon that works like a boomerang, but I don’t know how to make it go back to the player’s position. I tried watching tutorials, searching forums, and doing it by myself but I couldn’t figure it out. This is the basic weapon code that I have right now:

extends Area2D

var travelled_distance = 0

func _physics_process(delta):
	const SPEED = 75
	const RANGE = 100
	
	var direction = Vector2.RIGHT.rotated(rotation)
	position += direction * SPEED * delta
	
	travelled_distance += SPEED * delta
	if travelled_distance > RANGE:
		queue_free()

func _on_body_entered(body):
	queue_free()
	if body.has_method("take_damage"):
		body.take_damage()

I thought about doing something like this:

...
travelled_distance += SPEED * delta
	if travelled_distance >= RANGE and travelled_distance < (2 * RANGE):
		#Something here
	if travelled_distance > (2 * RANGE):
		queue_free()
...

but I have no idea of what to put after the first if. I am really just starting with Godot and game development in general, I would be really happy to get some help :smiley:

Think of it like this: Your boomerang has two states. In the first state it moves away from the player in some direction, until it gets far enough away. Then it switches to the second state, in which it moves towards the player until it gets close enough.

You can use a boolean variable to distinguish between the two states. Here’s pseudo-code:

var returning = false

func _physics_process(delta):
    if returning:
        move_towards_player()
        # add some logic here for what should happen
        # when it reaches the player
    else:
        move_away_from_player()
        if outside_of_range():
            returning = true

this works?

       var direction = Vector2.RIGHT.rotated(rotation)

       if travelled_distance >= RANGE and travelled_distance < (2 * RANGE):
		direction = -direction
	if travelled_distance > (2 * RANGE):
		queue_free()

	position += direction * SPEED * delta
	
	travelled_distance += SPEED * delta

Yes, thank you! It is not a perfect boomerang but I think it works for now!

1 Like