Last active
February 10, 2024 16:33
-
-
Save Birdasaur/a14c498a4f791e0053610e58aa1564b7 to your computer and use it in GitHub Desktop.
JavaFX 3D example on how to arbitrarily rotate one 3D Node to "look at" another.
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
public static Affine lookAt(Node node, Point3D from, Point3D to, boolean applyTranslate) { | |
//zVec is "forward" | |
Point3D zVec = to.subtract(from).normalize(); | |
//ydir is "up" | |
Point3D ydir = Rotate.Y_AXIS; | |
Point3D tangent0 = zVec.crossProduct(ydir); | |
//handle edge case where to location is precisely the "up" direction | |
if(tangent0.magnitude() < 0.001){ | |
//pick a different axis to use | |
ydir = Rotate.X_AXIS; | |
tangent0 = zVec.crossProduct(ydir); | |
} | |
tangent0.normalize(); | |
ydir = zVec.crossProduct(tangent0); | |
Point3D xVec = ydir.normalize().crossProduct(zVec).normalize(); | |
Point3D yVec = zVec.crossProduct(xVec).normalize(); | |
Affine affine = new Affine( | |
xVec.getX(), yVec.getX(), zVec.getX(), 0, | |
xVec.getY(), yVec.getY(), zVec.getY(), 0, | |
xVec.getZ(), yVec.getZ(), zVec.getZ(), 0); | |
if(applyTranslate){ | |
affine.setTx(from.getX()); | |
affine.setTy(from.getY()); | |
affine.setTz(from.getZ()); | |
} | |
node.getTransforms().setAll(affine); | |
return affine; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment