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

use atan2 to calculate angleBetween() #6205

Merged
merged 2 commits into from
Jun 14, 2023
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
19 changes: 10 additions & 9 deletions src/math/p5.Vector.js
Original file line number Diff line number Diff line change
Expand Up @@ -1637,15 +1637,16 @@ p5.Vector = class {
*/

angleBetween(v) {
const dotmagmag = this.dot(v) / (this.mag() * v.mag());
// Mathematically speaking: the dotmagmag variable will be between -1 and 1
// inclusive. Practically though it could be slightly outside this range due
// to floating-point rounding issues. This can make Math.acos return NaN.
//
// Solution: we'll clamp the value to the -1,1 range
let angle;
angle = Math.acos(Math.min(1, Math.max(-1, dotmagmag)));
angle = angle * Math.sign(this.cross(v).z || 1);
const magSqMult = this.magSq() * v.magSq();
// Returns NaN if either vector is the zero vector.
if (magSqMult === 0) {
return NaN;
}
const u = this.cross(v);
// The dot product computes the cos value, and the cross product computes
// the sin value. Find the angle based on them. In addition, in the case of
// 2D vectors, a sign is added according to the direction of the vector.
let angle = Math.atan2(u.mag(), this.dot(v)) * Math.sign(u.z || 1);
if (this.isPInst) {
angle = this._fromRadians(angle);
}
Expand Down
12 changes: 12 additions & 0 deletions test/unit/math/p5.Vector.js
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,18 @@ suite('p5.Vector', function() {
0.01
);
});

test('For the same vectors, the angle between them should always be 0.', function() {
v1 = myp5.createVector(288, 814);
v2 = myp5.createVector(288, 814);
expect(v1.angleBetween(v2)).to.equal(0);
});

test('The angle between vectors pointing in opposite is always PI.', function() {
v1 = myp5.createVector(219, 560);
v2 = myp5.createVector(-219, -560);
expect(v1.angleBetween(v2)).to.be.closeTo(Math.PI, 0.0000001);
});
});

suite('p5.Vector.angleBetween() [CLASS]', function() {
Expand Down