How to do a boomerang

Godot Version

extends Node2D

@export var speed = 75
@export var range = 200
@export var return_speed = 100

var travelled_distance = 0
var returning = false
var player_position = Vector2.ZERO

@onready var player = $“.”

@onready var sprite_2d = $Area2D/Sprite2D

Called when the node enters the scene tree for the first time.

func _ready():
player_position = player.global_position

func _physics_process(delta):
if Input.is_action_just_pressed(“click”) or Input.is_action_just_pressed(“attack”):
returning = true
sprite_2d.visible = true
position = player_position

if returning: 
	# Calculate direction towards the player
	var direction = (player_position - position).normalized()
	position += direction * return_speed * delta

	# Check if the boomerang has reached the player
	if position.distance_to(player_position) < 10:
		position = player.global_position
		returning = false
		# queue_free()
	# Move the boomerang in its initial direction
	var direction = Vector2.RIGHT.rotated(rotation)
	position += direction * speed * delta
	travelled_distance += speed * delta
	if travelled_distance >= range:
		returning = true

func _on_body_entered(body):
if not returning:


I want to make a boomerang for my 2d game but I´m not able to make out how to do it.
The boomerang starts moving from my position when I don´t press the attack buton and goes until the maximum range. Also when it returns it goes upper than my position and repeats the process spawning in random places. Please can someone help me?

Your script confuses me. Based on the line @onready var player = $"."” it seems to be attached to your player? But then all the comments suggest what it’s actually moving is the boomerang? :thinking:

Also, please format your code properly (by pressing the “</>” or using the shortcut Ctrl+E) and provide the Godot version you’re using (most importantly: 3 or 4?).

1 Like