From 46ba314ebb751214dffb63ed1465adededfd8ec7 Mon Sep 17 00:00:00 2001 From: Yorick van Klinken Date: Tue, 27 Aug 2024 16:45:04 +0200 Subject: [PATCH] feat: [#3171] normalize zero vector (#3179) Closes #3171 ## Changes: - `Vector.normalize()` return zero-vector (`(0,0)`) instead of `(0,1)` when normalizing a vector with a magnitude of 0 --- CHANGELOG.md | 1 + src/engine/Math/vector.ts | 12 ++++++------ 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 808264db4..ba1ff86db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ This project adheres to [Semantic Versioning](http://semver.org/). ### Breaking Changes +- `ex.Vector.normalize()` return zero-vector (`(0,0)`) instead of `(0,1)` when normalizing a vector with a magnitude of 0 - `ex.Gif` transparent color constructor arg is removed in favor of the built in Gif file mechanism - Remove core-js dependency, it is no longer necessary in modern browsers. Technically a breaking change for older browsers - `ex.Particle` and `ex.ParticleEmitter` now have an API that looks like modern Excalibur APIs diff --git a/src/engine/Math/vector.ts b/src/engine/Math/vector.ts index 95524904d..b7e281a96 100644 --- a/src/engine/Math/vector.ts +++ b/src/engine/Math/vector.ts @@ -227,15 +227,15 @@ export class Vector implements Clonable { } /** - * Normalizes a vector to have a magnitude of 1. + * Normalizes a non-zero vector to have a magnitude of 1. Zero vectors return a new zero vector. */ public normalize(): Vector { - const d = this.distance(); - if (d > 0) { - return new Vector(this.x / d, this.y / d); - } else { - return new Vector(0, 1); + const distance = this.distance(); + if (distance === 0) { + return Vector.Zero; } + + return new Vector(this.x / distance, this.y / distance); } /**