← Pixel Dreamer Studio

Turn towards a target the short way round

Turn by angle_difference(current, wanted), limited to a number of degrees per second.

Turn by angle_difference(rotation.y, wanted), limited to a set number of degrees per second, instead of moving rotation.y straight towards the wanted angle. In our Godot 4.7 test a turret facing 170 degrees with a target at -170 degrees, only 20 degrees away across the back, turned 340 degrees the long way round with move_toward() and took 1.90 s at 180 degrees a second. The script turned 20 degrees in 0.12 s.

The code

Attach this to the part that turns: the turret, the cannon, or the whole ship or enemy. Set target. The node's -Z, Godot's forward, turns to point at the target at turn_speed degrees a second.

extends Node3D
## Turns this node to face a target the short way round, at a set speed: a turret, a ship's cannon, an enemy's head.
## Set target. The node's -Z, Godot's forward, ends up pointing at it.

@export var target: Node3D
@export var turn_speed := 180.0  ## degrees per second


func _physics_process(delta: float) -> void:
	if target == null:
		return
	var to := target.global_position - global_position
	var want := atan2(-to.x, -to.z)  # the rotation.y that points -Z at the target
	var diff := angle_difference(rotation.y, want)  # always between -180 and 180 degrees: the short way
	var step := deg_to_rad(turn_speed) * delta
	rotation.y = wrapf(rotation.y + clampf(diff, -step, step), -PI, PI)

What we measured

Turning at 180 degrees a second, stepped at 60 frames a second. We added up how far the turret turned until it faced the target within half a degree. Two runs gave the same numbers.

Why it goes the long way

Godot gives angles from -180 to 180 degrees, so 170 and -170 look 340 apart as plain numbers, although they are 20 degrees apart across the back. move_toward() and lerp() only see the numbers. angle_difference() always answers with the shortest turn, between -180 and 180 degrees, and wrapf() keeps the angle in that range however many times the turret goes round.

What to change

Effects for the cannons: Naval & Pirate VFX for Godot 4 has 24 presets, including Cannon Fire, Broadside Volley, Cannonball Trail, Cannonball Splash, hits on wood, Deck Fire, Ship Sinking and Bow Wake, 8 of them also in a PSX version.

Tested in Godot 4.7 with the Compatibility renderer.

Ready-made: Naval & Pirate VFX for Godot 4 has 24 ready-made ship battle effects, including Cannon Fire, Broadside Volley, Cannonball Splash, Deck Fire and Ship Sinking.

More how-tos for Naval & Pirate VFX for Godot 4: Boat wake particles that follow the speed

More how-tos: Projectiles and aiming