Skip to content
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
Fix vector reflect() mutating surface normal arg (#7088)
  • Loading branch information
nbogie committed Jun 8, 2024
commit 01cb9d25a09a875dc96d6398a3a49fed35e616dd
4 changes: 2 additions & 2 deletions src/math/p5.Vector.js
Original file line number Diff line number Diff line change
Expand Up @@ -2972,8 +2972,8 @@ p5.Vector = class {
* </div>
*/
reflect(surfaceNormal) {
surfaceNormal.normalize();
return this.sub(surfaceNormal.mult(2 * this.dot(surfaceNormal)));
const surfaceNormalCopy = p5.Vector.normalize(surfaceNormal);
return this.sub(surfaceNormalCopy.mult(2 * this.dot(surfaceNormalCopy)));
}

/**
Expand Down
31 changes: 31 additions & 0 deletions test/unit/math/p5.Vector.js
Original file line number Diff line number Diff line change
Expand Up @@ -1646,6 +1646,21 @@ suite('p5.Vector', function() {
0.01
);
});
test('should not update surface normal', function() {
const tolerance = 0.001;
assert.closeTo(x_normal.x, 3, tolerance);
assert.closeTo(x_normal.y, 0, tolerance);
assert.closeTo(x_normal.z, 0, tolerance);

assert.closeTo(y_normal.x, 0, tolerance);
assert.closeTo(y_normal.y, 3, tolerance);
assert.closeTo(y_normal.z, 0, tolerance);

assert.closeTo(z_normal.x, 0, tolerance);
assert.closeTo(z_normal.y, 0, tolerance);
assert.closeTo(z_normal.z, 3, tolerance);
});

});

suite('p5.Vector.reflect() [CLASS]', function() {
Expand Down Expand Up @@ -1696,6 +1711,22 @@ suite('p5.Vector', function() {
expect(z_bounce_incoming).to.not.equal(z_bounce_outgoing);
});

test('should not update surface normal', function() {
const tolerance = 0.001;
assert.closeTo(x_normal.x, 3, tolerance);
assert.closeTo(x_normal.y, 0, tolerance);
assert.closeTo(x_normal.z, 0, tolerance);

assert.closeTo(y_normal.x, 0, tolerance);
assert.closeTo(y_normal.y, 3, tolerance);
assert.closeTo(y_normal.z, 0, tolerance);

assert.closeTo(z_normal.x, 0, tolerance);
assert.closeTo(z_normal.y, 0, tolerance);
assert.closeTo(z_normal.z, 3, tolerance);
});


test('should update target', function() {
assert.equal(x_target, x_bounce_outgoing);
assert.equal(y_target, y_bounce_outgoing);
Expand Down