Created
October 26, 2025 15:22
-
-
Save justADeni/e11591b2e7999ce5b5c40aee1bb671b4 to your computer and use it in GitHub Desktop.
Rotate a vector about a center at angle and axis
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import org.joml.Quaternionf; | |
| import org.joml.Vector3f; | |
| public class Main { | |
| public static void main(String[] args) { | |
| Vector3f display = new Vector3f(0,10,0); | |
| Vector3f center = new Vector3f(0,0,0); | |
| float angle = 90f; | |
| Vector3f axis = new Vector3f(1,0,0); | |
| Vector3f result = rotateAround(display, center, (float) Math.toRadians(angle), axis); | |
| Vector3f relative = new Vector3f(result).sub(display.x, display.y, display.z); | |
| System.out.printf("Rotated display %s around center %s at an angle of %.2f and axis %s%n", vecToString(display), vecToString(center), angle, vecToString(axis)); | |
| System.out.printf("With the result: %s, relative to itself: %s", vecToString(result), vecToString(relative)); | |
| } | |
| public static Vector3f rotateAround(Vector3f point, Vector3f center, float angleRad, Vector3f axis) { | |
| Quaternionf q = new Quaternionf().fromAxisAngleRad(axis.normalize(new Vector3f()), angleRad); | |
| Vector3f result = new Vector3f(point).sub(center); | |
| q.transform(result); | |
| result.add(center); | |
| return result; | |
| } | |
| public static String vecToString(Vector3f vector3f) { | |
| return String.format("(%.2f|%.2f|%.2f)", vector3f.x, vector3f.y, vector3f.z); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment