Godot Version
4.6.1
Question
I am using rotate_toward on my mesh to make a turret follow the player. Problem is when the player is circling the turret it goes beyond 360 and that leads to a problem with my is_equal_approx() to check if the turret has caught up with the player:
func targetObjet(object, delta):
if object:
var targetVector = (object.global_position - self.global_position)
var direction_angle = Vector2(targetVector.x, targetVector.z).angle_to(Vector2.UP)
var distanceToTarget = abs(targetVector.length())
$MeshInstance3D/TurretHead.rotation.y = rotate_toward($MeshInstance3D/TurretHead.rotation.y, direction_angle, delta * rotation_speed)
if distanceToTarget <= self.range:
var textAngle = "direction_angle: " + str(rad_to_deg(direction_angle))
var turretAngle = "turretAngle: " + str(rad_to_deg($MeshInstance3D/TurretHead.rotation.y))
DebugDraw3D.draw_text(self.global_position + self.global_basis.y * 5.85, textAngle, 128)
DebugDraw3D.draw_text(self.global_position + self.global_basis.y * 6.85, turretAngle, 128)
if is_equal_approx((direction_angle), ($MeshInstance3D/TurretHead.rotation.y)):
...rest of the code here
I KNOW it’s gonna be a super simple answer but I just can’t wrap my head around it
You could fmod() the turret’s rotation
if is_equal_approx((direction_angle), fmod($MeshInstance3D/TurretHead.rotation.y, TAU)):
Thanks for the hint! I had to adjust the code as well at two other steps to ensure that the rad value of both the turret and direction_angle are never below 0 and now it works like a charm
func targetObjet(object, delta):
if object:
var targetVector = (object.global_position - self.global_position)
var direction_angle = Vector2(targetVector.x, targetVector.z).angle_to(Vector2.UP)
var distanceToTarget = abs(targetVector.length())
$MeshInstance3D/TurretHead.rotation.y = rotate_toward($MeshInstance3D/TurretHead.rotation.y, direction_angle, delta * rotation_speed)
if direction_angle < 0:
direction_angle += TAU
if fmod($MeshInstance3D/TurretHead.rotation.y, TAU) < 0:
$MeshInstance3D/TurretHead.rotation.y += TAU
if distanceToTarget <= self.range:
var textAngle = "direction_angle: " + str(direction_angle)
var turretAngle = "turretAngle: " + str($MeshInstance3D/TurretHead.rotation.y)
var fmodTurretAngle = "fmodTurretAngle: " + str(fmod($MeshInstance3D/TurretHead.rotation.y, TAU))
DebugDraw3D.draw_text(self.global_position + self.global_basis.y * 5.85, textAngle, 128)
DebugDraw3D.draw_text(self.global_position + self.global_basis.y * 6.85, turretAngle, 128)
DebugDraw3D.draw_text(self.global_position + self.global_basis.y * 7.85, fmodTurretAngle, 128)
if is_equal_approx((direction_angle), fmod($MeshInstance3D/TurretHead.rotation.y, TAU)):
...