How to Calculate the difference between two values that wrap around?

Godot Version

4.2.2

Question

How do I calculate the difference between two variables that wrap around? To be Specific: How do I take a Hue of Color X, and the Hue of Color Y, then compare their values (via subtraction) to see how far apart they are. Out of the box the solution would be to simply subtract them within an absf() however Hue 0.1 visually isn’t far from Hue 1.0, but is numerically vast.

Interesting question. This seems to work well.

extends Node2D

var hue_1: float = 0.1
var hue_2: float = 0.8


func _ready() -> void:
	var answer: float = calculate_hue_difference(hue_1, hue_2)
	print(answer)
	
func calculate_hue_difference(value_1: float, value_2: float) -> float:
	return min(abs(value_1 - value_2), 1 - abs(value_1 - value_2))

# prints 0.3

But then I was thinking what if you wanted to do it with wrapping of more than 1.0, so added the max option.


func _ready() -> void:
	var answer: float = calculate_hue_difference(hue_1, hue_2, 2.0)
	print(answer)

func calculate_hue_difference(value_1: float, value_2: float, max_value: float = 1.0) -> float:
	return min(abs(value_1 - value_2), max_value - abs(value_1 - value_2))

But I think the first version is fine for just hue’s. (You may want to add a verification that the two values are less than 1, otherwise it can return a -ve number in some cases.)

Hope that helps, not sure it is the best way but it seems to work when I tested it.

2 Likes

Thank you Paul!

I had a suspicion it could be as simple as basing the comparison off of 1, but I wasn’t entirely sure and began mentally spiraling through solutions that convert the values into Degrees so I may utilize the @GlobalScope.angle_difference function.

I should probably brush up on my mathematics lol.

1 Like

See also angle_difference():

That operates on a range of 0..2π, so you might have to scale your input, but it gives you the minimum distance between two wrapping values.