Skip to content
Open
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
6 changes: 6 additions & 0 deletions src/math/p5.Vector.js
Original file line number Diff line number Diff line change
Expand Up @@ -2228,13 +2228,19 @@ 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);
this.y = m * Math.sin(a);
return this;
}



/**
* Rotates a 2D vector by an angle without changing its magnitude.
*
Expand Down
11 changes: 11 additions & 0 deletions test/unit/math/p5.Vector.js
Original file line number Diff line number Diff line change
@@ -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';
Expand Down