Skip to content

Commit

Permalink
Quat: add the static sFromTo() method
Browse files Browse the repository at this point in the history
  • Loading branch information
stephengold committed Sep 30, 2024
1 parent a44f714 commit 8e68ec6
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/main/java/com/github/stephengold/joltjni/Quat.java
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,31 @@ public void set(float x, float y, float z, float w) {
this.w = w;
}

/**
* Create a rotation quaternion that rotates {@code from} to {@code to}.
*
* @param from the first direction vector (not null, unaffected)
* @param to the 2nd direction vector (not null, unaffected)
* @return a new quaternion
*/
public static Quat sFromTo(Vec3Arg from, Vec3Arg to) {
float lenV1V2 = (float) Math.sqrt(from.lengthSq() * to.lengthSq());
float w = lenV1V2 + from.dot(to);

if (w == 0f) {
if (lenV1V2 == 0f) { // one of the vectors has zero length
return Quat.sIdentity();
} else { // vectors are perpendicular
Vec3 v = from.getNormalizedPerpendicular();
return new Quat(v, 0f);
}
}

Vec3 v = from.cross(to);
Quat result = new Quat(v, w).normalized();
return result;
}

/**
* Create an identity quaternion (0,0,0,1).
*
Expand Down

0 comments on commit 8e68ec6

Please sign in to comment.