kreaTTo
kreaTTo

Reputation: 23

How would I update an angle, but only within a certain range?

Basically, I have an angle that can only change a certain "turn radius" (say, 60/256 of a rotation) each time it updates. It is changed by an input angle that could be any angle. I need to clamp this input angle so that if it is outside of the turn radius, it will go to the nearest valid angle

For example:

or

or

I am not sure exactly how to properly wrap the angle, so I'm a bit stuck here.

Upvotes: 1

Views: 209

Answers (2)

kreaTTo
kreaTTo

Reputation: 23

Based on @robert-lozyniak's answer, this is what I ended up with:

fn clamp_angle_update(angle: u8, target: u8, limit: u8) -> u8 {
    let mut difference = target as isize - angle as isize;

    // normalize the difference
    difference += 256 + 256 / 2;
    difference %= 256;
    difference -= 256 / 2;

    let limit = limit as isize;
    difference = if difference > limit {
        limit
    } else if difference < -limit {
        -limit
    } else { difference };

    // add the difference to the original angle
    let mut angle = angle as isize + difference;

    // normalize the angle
    angle %= 256;
    angle += 256;
    angle %= 256;

    angle as u8
}

Upvotes: 0

Robert Lozyniak
Robert Lozyniak

Reputation: 322

First, find the difference between the original angle and the input angle. (Just subtract.) Then, "normalize" this difference to between -180 degrees and 180 degrees.

normalized_difference = (((( raw_difference % 360) + 540) % 360) - 180)

Then, if the "normalized" difference is outside the desired range, change it to be within range. Then add the (possibly changed) normalized difference to the original angle to get the output angle. If you wish to normalize the output angle to between 0 degrees and 359.99... degrees, you can do it thus:

normalized_angle = (((raw_angle % 360) + 360) % 360)

Upvotes: 1

Related Questions