Crocsx
Crocsx

Reputation: 7640

Make sure the values interpolate correctly when they wrap around 360 degrees

I have the following Lerp function

  public static headingPitchRollLerp(v1: HeadingPitchRoll, v2: HeadingPitchRoll, t: number): HeadingPitchRoll {
    Math.min(Math.max(t, 0), 1);
    const result = new Cesium.HeadingPitchRoll();
    result.heading = v1.heading + (v2.heading - v1.heading) * t;
    result.pitch = v1.pitch + (v2.pitch - v1.pitch) * t;
    result.roll = v1.roll + (v2.roll - v1.roll) * t;
    return result;
  }

It works great when the rotation do not go over and under 360'.

But if for exemple, I have a heading at 350' and my v2 has a heading at 10', instead of going from 350' to 10' (only 20') my code move back and redo a full rotation (340').

What can I change to make the rotation always be the smallest?

Upvotes: 0

Views: 275

Answers (2)

Niilo Keinänen
Niilo Keinänen

Reputation: 2582

Not related to the question, but as far as I'm aware

Math.min(Math.max(t, 0), 1);

doesn't actually change the value of "t". It would be necessary to reassign it

t = Math.min(Math.max(t, 0), 1);

Upvotes: 1

Crocsx
Crocsx

Reputation: 7640

I fixed with the following

  public static headingPitchRollLerp(v1: HeadingPitchRoll, v2: HeadingPitchRoll, t: number): HeadingPitchRoll {
    Math.min(Math.max(t, 0), 1);
    const result = new Cesium.HeadingPitchRoll();

    const v1H = ((v2.heading - v1.heading) > Math.PI) ? v1.heading += 2 * Math.PI : ((v2.heading - v1.heading) < -Math.PI) ? v1.heading -= 2 * Math.PI : v1.heading;
    const v1P = ((v2.pitch - v1.pitch) > Math.PI) ? v1.pitch += 2 * Math.PI : ((v2.pitch - v1.pitch) < -Math.PI) ? v1.pitch -= 2 * Math.PI : v1.pitch;
    const v1R = ((v2.roll - v1.roll) > Math.PI) ? v1.roll += 2 * Math.PI : ((v2.roll - v1.roll) < -Math.PI) ? v1.roll -= 2 * Math.PI : v1.roll;

    result.heading = v1H + (v2.heading - v1H) * t;
    result.pitch = v1P + (v2.pitch - v1P) * t;
    result.roll = v1R + (v2.roll - v1R) * t;
    return result;
  }

Upvotes: 0

Related Questions