How to calculate difference between two rotations?

Godot Version

4.2.1

Intro

I’m making a game where you have to put something down at just the right angle.

The thing on which you put it down (the holder), is set at a difference angle every new game in degrees between 0 and 360. But let’s not take that in account and assume it’s just at 0 degrees.

The thing you put down (the item) is rotating slowly and once it touches the holder, rotation will stop and the difference should be calculated.

It doesn’t matter if the item is rotated 180 degrees and put down on the holder or if it’s at a 0 degrees difference.

This is what I have so far:
no_1 is the item.rotation_degrees.y
no_2 is the holder.rotation_degrees.y

func calculate_difference(no_1, no_2):
    if no_1 >= 180:
    	no_1 -= 180
    
    if no_2 >= 180:
    	no_2 -= 180
    
    if no_1 > no_2:
    	return no_1 - no_2
    else: 
    	return no_2 - no_1

First of all, the two if statements at the top don’t work, somehow. So when rotating_degrees is bigger than 180, it doesn’t subtract 180.

And second, I don’t know how to take in account that if the item is rotated at 350 degrees, the difference should be 10 degrees. And not 350 or with the -180 rule, 170 degrees.

Question

So how should I go about this, to work out the difference and take in account that the item can either be at 0 or 180 degrees and that, for example, a result of 352 degrees is actually really close?

I’m very much a beginner when it comes to Godot, so please excuse any obvious mistakes.

In this example I’m assuming that no_1 and no_2 are within the range (0, 360) and the calculated difference should be unsigned.

func calculate_difference(no_1, no_2):
    var angle = abs(no_1 - no_2)
    if angle > 180.0:
        return 360.0 - angle
    return angle

So you just take the difference between the inputs to get an angle, and if the angle goes the long way around the circle, take its compliment.

If you want to have symmetry, so that 0 and 180 degrees are the same thing, just halve the values.

func calculate_difference(no_1, no_2):
    var angle = abs(no_1 - no_2)
    if angle > 90.0:
        return 180.0 - angle
    return angle

Forcing the angles to a specific range can be easily done with fposmod().

no_1 = fposmod(no_1, 180.0)
no_2 = fposmod(no_2, 180.0)

This works perfectly, thank you!

And your assumptions were correct. When the degrees get below 0, I set them to 360 and vice versa. And the difference should always be positive.

Thanks again.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.