Need some help figuring out problems with rotation calculation

Godot Version

4.4.1.stable

Question

Hi!

I’m currently working on refining a knob UI element that i made for my game. The code that handles its rotation looks like this:

func follow_mouse():
var mouse_angle = get_global_mouse_position().angle_to_point(self.global_position) - offset
var deg_mouse_angle = rad_to_deg(mouse_angle)
#converts the degrees to 360 to make them more workable
var mouse_angle_360 = angle_360(deg_mouse_angle)
print(mouse_angle_360)
$Sprite2D.rotation = mouse_angle
#converts the sprite rotation into percentage
value_percent()

I’m having some trouble with the “offset” variable. I have added just today to make the knob consider the initial click position the starting point of rotation, rather than instantly snap to the mouse position. The code for calculating offset runs on mouse click and looks like this:

offset = get_global_mouse_position().angle_to_point(self.global_position) - $Sprite2D.rotation

However, there’s now a bug that allows the percentage to overflow past or below 100. After some debugging it seems that the issue lies withing the initial mouse_angle calculation, specifically with the fact that it can somehow overflow past or below 360.
I can’t quite figure out the conditions for the bug to occur, however it seems to occur pretty regularly after some interaction with the knob. I’ll add a video do demonstrate this.
I’m sure this is just a math problem, though i’m really struggling to figure this out, so i would appreciate if somebody could help.

If the problem is with percentage then calculations you’re doing in value_percent() might be responsible.

Not really. The issue is most certainly with the mouse_angle calculation as its value can overflow past 6 rad, so past the 360 degress, and as such result in percentage higher than 100.

You can wrap it to 0 - 360 range when calculating the percentage so it shouldn’t matter if it goes over/under as long as the direction is correct.