Difficult to produce a test case for you but here goes. Just add this script to any Node2D.
extends Node2D
var start_rotation: float = 0 # The direction you are facing
var current_rotation: float = 0
var rotation_range: float = 45 # The rotation range in each direction
var input_rotation: int = 0 # 1 or -1 depending on left/right input
var rotation_speed: int = 20 # just for turning speed
# Just so you can test the rotations with left/right inputs
func _input(event):
if event.is_action_pressed("ui_right"):
input_rotation = 1
elif event.is_action_pressed("ui_left"):
input_rotation = -1
func _process(delta):
# Calculate the new rotation
var new_rotation = current_rotation + input_rotation * delta * rotation_speed
# Calculate the relative rotation from the start position
var relative_rotation = wrapf(new_rotation - start_rotation, -180, 180)
# Clamp the relative rotation
relative_rotation = clamp(relative_rotation, -rotation_range, rotation_range)
# Calculate the final rotation
current_rotation = wrapf(start_rotation + relative_rotation, 0, 360)
# Print for testing
print("Current Rotation: ", current_rotation)
When you press left, the current rotation rotates until it reaches the maximum angle from the start_rotation. Same for pressing ui_right.
You can change the start_rotation to test to other angles.
I hope you can apply this to your particular case. What we do is store the initial rotation value, then add the rotation direction * rotate_speed * delta like normal to get the new rotation.
We then find the relative rotation from the start position by using wrapf for -180 to 180.
We then clamp this to your rotation limitations.
We then add this relative rotation back to the starting rotation and wrapf it again to deal with crossing over the 0 point again.
Anyway, you can see from the print out in the console that it achieves your rotation goals and you can change the start_rotation to test it for different starting directions.
Hope that helps.
PS Here it is without the comments:
extends Node2D
var start_rotation: float = 0
var current_rotation: float = 0
var rotation_range: float = 45
var input_rotation: int = 0
var rotation_speed: int = 20
func _input(event):
if event.is_action_pressed("ui_right"):
input_rotation = 1
elif event.is_action_pressed("ui_left"):
input_rotation = -1
func _process(delta):
var new_rotation = current_rotation + input_rotation * delta * rotation_speed
var relative_rotation = wrapf(new_rotation - start_rotation, -180, 180)
relative_rotation = clamp(relative_rotation, -rotation_range, rotation_range)
current_rotation = wrapf(start_rotation + relative_rotation, 0, 360)
print("Current Rotation: ", current_rotation)