Skip to content

Instantly share code, notes, and snippets.

@jmpinit
Created April 21, 2023 15:50
Show Gist options
  • Save jmpinit/8a66d5bc8ea552d95d181e1adcfe580e to your computer and use it in GitHub Desktop.
Save jmpinit/8a66d5bc8ea552d95d181e1adcfe580e to your computer and use it in GitHub Desktop.
Flip a 3D point over a line defined by two 3D points
export function flipPointOverLine(linePoint1, linePoint2, point) {
// Calculate the vector that represents the line direction
const lineVector = vec3.create();
vec3.subtract(lineVector, linePoint2, linePoint1);
vec3.normalize(lineVector, lineVector);
// Calculate the projection of the point onto the line
// relative to the start of the line
const pointToLinePoint1 = vec3.subtract(vec3.create(), point, linePoint1);
const dotProduct = vec3.dot(pointToLinePoint1, lineVector);
const projection = vec3.scale(vec3.create(), lineVector, dotProduct);
// Calculate the reflection of the point across the line
const reflection = vec3.create();
vec3.subtract(reflection, pointToLinePoint1, projection);
vec3.scale(reflection, reflection, -1);
vec3.add(reflection, reflection, projection);
// Add the start of the line to the reflection to get the
// absolute position of the reflection
const absoluteReflection = vec3.add(vec3.create(), linePoint1, reflection);
return absoluteReflection;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment