Skip to content

Commit

Permalink
Merge pull request #7103 from nbogie/bugfix-vector-reflect
Browse files Browse the repository at this point in the history
Fix vector reflect() mutating surface normal arg (#7088)
  • Loading branch information
limzykenneth authored Jun 24, 2024
2 parents c2aad9e + 01cb9d2 commit eb61f7a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
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

0 comments on commit eb61f7a

Please sign in to comment.