From 922ff97583764714e7d18cb36c877becc20c8f94 Mon Sep 17 00:00:00 2001 From: Ali Shakiba Date: Mon, 23 Dec 2024 18:06:04 +0330 Subject: [PATCH] Add static Vec2.normalize --- .changeset/clever-pants-carry.md | 5 +++++ src/common/Vec2.ts | 14 ++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 .changeset/clever-pants-carry.md diff --git a/.changeset/clever-pants-carry.md b/.changeset/clever-pants-carry.md new file mode 100644 index 00000000..0fc5e45a --- /dev/null +++ b/.changeset/clever-pants-carry.md @@ -0,0 +1,5 @@ +--- +"planck": patch +--- + +Add static Vec2.normalize diff --git a/src/common/Vec2.ts b/src/common/Vec2.ts index 13790f7d..633b4fcf 100644 --- a/src/common/Vec2.ts +++ b/src/common/Vec2.ts @@ -363,6 +363,20 @@ export class Vec2 { return length; } + /** + * Returns a new unit vector from the provided vector. + * + * @returns new unit vector + */ + static normalize(v: Vec2Value): Vec2 { + const length = Vec2.lengthOf(v); + if (length < EPSILON) { + return Vec2.zero(); + } + const invLength = 1.0 / length; + return Vec2.neo(v.x * invLength, v.y * invLength); + } + /** * Get the length of this vector (the norm). *