This is the script I use to make a CharacterBody2D enemy jump to a particular position. I should also work for arrows.
Can’t remember where I got the code though, but it works for me.
You can add this script to your arrow scene and call shoot_arrow
extends CharacterBody2D
##Assuming this is the arrow scene
func shoot_arrow():
velocity = calculate_arc_velocity(global_position, enemy.global_position, gravity)
func calculate_arc_velocity(start_position, target_position, arc_height, gravity):
var jump_velocity = Vector2()
var displacement = target_position - start_position
if displacement.y > arc_height:
var time_up = sqrt(-2 * arc_height / float(gravity))
var time_down = sqrt(2 * (displacement.y - arc_height) / float(gravity))
#print("time %s" % (time_up + time_down))
jump_velocity.y = -sqrt(-2 * gravity * arc_height)
jump_velocity.x = displacement.x / float(time_up + time_down)
return jump_velocity
func physics_process(_delta):
velocity.y += gravity * _delta
move_and_slide()