Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add static Reflect function to Vector3 #13281

Merged
merged 5 commits into from
Nov 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions packages/dev/core/src/Maths/math.vector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2515,6 +2515,30 @@ export class Vector3 {
return result;
}

/**
* Reflects a vector off the plane defined by a normalized normal
* @param inDirection defines the vector direction
* @param normal defines the normal - Must be normalized
* @returns the resulting vector
*/
public static Reflect<T extends Vector3>(inDirection: DeepImmutable<Vector3>, normal: DeepImmutable<Vector3>): Vector3 {
return this.ReflectToRef(inDirection, normal, new Vector3());
}

/**
* Reflects a vector off the plane defined by a normalized normal to reference
* @param inDirection defines the vector direction
* @param normal defines the normal - Must be normalized
* @param result defines the Vector3 where to store the result
* @returns the resulting vector
*/
public static ReflectToRef<T extends Vector3>(inDirection: DeepImmutable<Vector3>, normal: DeepImmutable<Vector3>, ref: T): T {
const tmp = TmpVectors.Vector3[0];
tmp.copyFrom(normal).scaleInPlace(2 * Vector3.Dot(inDirection, normal));

return ref.copyFrom(inDirection).subtractInPlace(tmp);
}

/**
* @internal
*/
Expand Down
10 changes: 10 additions & 0 deletions packages/dev/core/test/unit/Math/babylon.math.vector.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,16 @@ describe("Babylon Vectors", () => {
expect(rayGoingThrough.projectOnPlane(simplePlane, rayOrigin)).toEqual(expected);
});

it("can reflect off the plane defined by a normal", () => {
const inDirection = new Vector3(10, 10, 5);

const normal = Vector3.Right();

const expected = new Vector3(-10, 10, 5);

expect(Vector3.Reflect(inDirection, normal)).toEqual(expected);
});

describe("can get angle between vectors on a plane", () => {
BabylonMathVectorGetAngleBetweenVectorsOnPlaneTestCases.forEach(({ v0, v1, normal, result }, index) => {
const v0Vector = new Vector3(v0.x, v0.y, v0.z);
Expand Down