I’m trying to code a boomerang (as a RigidBody) in a top down 2D game. It’s instantiated on a click, and the player throws it towards mouse_global_position. No matter what direction that is though, the constant forces I’ve set use the scene’s x and y, and don’t take into account where it started. Right now I can only get the boomerang effect of coming back to the player if I throw it to the left:
My bad if I didn’t explaing this too well. Would love some advice on how to proceed (I’m not too hot on vector math).
Try setting the constant force to the opposite direction of the force you applied to throw it. You can do this by seeing constant force to the throwing force multiplied by a negative number.
add_constant_force uses a local offset. So that position moves with the rigidbody, if you add a constant force to the right, it’ll always be applied to the right no matter how the rigidbody moves.
If you want a constant force towards a point, you’d need to update it each frame.
Here’s a proof of concept
The boomerang script is as simple as:
extends RigidBody2D
var origin_position : Vector2
var ACCELERATION_FORCE := 10.0
func _physics_process(_delta: float) -> void:
var dir = (origin_position - position).normalized()
add_constant_force(dir * ACCELERATION_FORCE)
With the origin_position being where it was spawned at, and where it tries to return to. You might want to use the player’s position instead of this, so it returns to the player even if the player has moved.