← Pixel Dreamer Studio

Hit the target with an arcing shot at any angle and height

Solve the launch speed from the distance, the height difference and the angle, instead of sqrt(gravity * distance).

For a fixed launch angle a, use speed = sqrt(g d² / (2 cos²a (d tan a - h))), where d is the flat distance and h how much higher the target is. The shortcut sqrt(gravity * distance) is only right on flat ground at 45 degrees. In our Godot 4.7 test it missed a target 5 m higher and 40 m away by 6.14 m. The script missed by 0.29 m.

The code

Call launch_velocity(muzzle_position, target_position) and give the result to your projectile as its starting velocity, then apply gravity to it every frame. Use the same gravity value your projectile uses. A result of Vector3.ZERO means the target is too high to reach at this angle: raise the angle or pick another target.

extends Node
## Launch velocity to hit a target at a fixed angle: catapult, trebuchet, mortar, grenade.
## Works when the target is higher or lower than the launcher. Returns Vector3.ZERO when
## the target cannot be reached at this angle (too high for it).

@export var angle_degrees := 45.0
@export var gravity := 9.8


func launch_velocity(from: Vector3, to: Vector3) -> Vector3:
	var flat := Vector3(to.x - from.x, 0.0, to.z - from.z)
	var d := flat.length()
	var h := to.y - from.y  # positive = target is higher
	var a := deg_to_rad(angle_degrees)
	var denom := 2.0 * cos(a) * cos(a) * (d * tan(a) - h)
	if d < 0.001 or denom <= 0.0:
		return Vector3.ZERO
	var speed := sqrt(gravity * d * d / denom)
	return flat.normalized() * speed * cos(a) + Vector3.UP * speed * sin(a)

What we measured

We flew each shot at 60 steps per second, the usual way: subtract gravity from the velocity, then move by the velocity. We measured how far from the target it was when it came down to the target's height. Gravity 9.8, two runs with the same numbers.

Why it happens

sqrt(g d) comes from the range formula for flat ground, and at 45 degrees the angle terms cancel out. Change the angle or put the target on a wall or down a cliff and it no longer applies. The 0.1 to 0.3 m the script still misses by comes from moving in 1/60 second steps, while the formula assumes smooth motion. Splash damage or a hit radius of half a meter covers it.

What to change

Draw the path before you fire: predict a trajectory line.

The launch and the landing: Medieval Warfare & Siege VFX for Godot 4 has Trebuchet Launch, Boulder Impact, Wall Hit, Wall Breach and Fire Pot Impact.

Tested in Godot 4.7 with the Compatibility renderer.

Ready-made: Medieval Warfare & Siege VFX for Godot 4 has Trebuchet Launch, Boulder Impact, Wall Hit, Wall Breach, Fire Pot Impact and Arrow Volleys that arc and stick in the ground.

More how-tos for Medieval Warfare & Siege VFX for Godot 4: Drag a box to select 3D units, in any direction · Move a group of units without a pile-up

More how-tos: Projectiles and aiming