diff --git a/src/math/p5.Vector.js b/src/math/p5.Vector.js index f54667f6ee..9cbdecff94 100644 --- a/src/math/p5.Vector.js +++ b/src/math/p5.Vector.js @@ -2228,6 +2228,10 @@ p5.Vector = class { */ setHeading(a) { + if (this.z !== undefined && this.z !== 0) { + throw new Error('setHeading() is only supported for 2D vectors.'); + } + if (this.isPInst) a = this._toRadians(a); let m = this.mag(); this.x = m * Math.cos(a); @@ -2235,6 +2239,8 @@ p5.Vector = class { return this; } + + /** * Rotates a 2D vector by an angle without changing its magnitude. * diff --git a/test/unit/math/p5.Vector.js b/test/unit/math/p5.Vector.js index ef3570ee0b..ab7a743c2d 100644 --- a/test/unit/math/p5.Vector.js +++ b/test/unit/math/p5.Vector.js @@ -1,3 +1,14 @@ +suite('p5.Vector.prototype.setHeading (invalid dimensions)', function () { + test('throws an error for vectors with non-zero z component', function () { + let v3 = new p5.Vector(1, 2, 3); + + assert.throws(() => { + v3.setHeading(Math.PI / 2); + }, Error); + }); +}); + + suite('p5.Vector', function() { var RADIANS = 'radians'; var DEGREES = 'degrees';