1
0
Fork 0
Browse Source

feat: add new function to rotate a vector

Signed-off-by: André Jaenisch <andre.jaenisch@posteo.de>
combat-scorched-earth-from-outer-space
André Jaenisch 9 months ago
parent
commit
a5dd1755d9
Signed by: ryuno-ki
GPG Key ID: 5A668E771F1ED854
  1. 18
      src/js/vector.js
  2. 17
      test/js/vector.test.js
  3. 8
      types/vector.d.ts

18
src/js/vector.js

@ -100,3 +100,21 @@ export function distance (v, w) {
export function normalize (v) {
return scale(v, 1 / (length(v) || 1))
}
/**
* Rotate a vector around a given centre for a given angle in radians.
*
* @param {Vector2D} v
* @param {Vector2D} centre
* @param {number} angle
*/
export function rotate (v, centre, angle) {
const { cos, sin } = Math
const x = v.x - centre.x
const y = v.y - centre.y
return Vec2(
x * cos(angle) - y * sin(angle) + centre.x,
x * sin(angle) + y * cos(angle) + centre.y
)
}

17
test/js/vector.test.js

@ -7,6 +7,7 @@ import {
dot,
length,
normalize,
rotate,
scale,
subtract,
Vec2,
@ -140,4 +141,20 @@ describe('Vector library', function () {
expect(normalized.y).to.be.approximately(0.8, 0.001)
})
})
describe('rotate', function () {
it('should rotate a shape around its centre on given angle', function () {
// Arrange
const v = Vec2(1, 0)
const c = Vec2(0, 0)
const angle = Math.PI
// Act
const rotated = rotate(v, c, angle)
// Assert
expect(rotated.x).to.be.approximately(-1, 0.001)
expect(rotated.y).to.be.approximately(0, 0.001)
})
})
})

8
types/vector.d.ts vendored

@ -73,6 +73,14 @@ export function distance(v: Vector2D, w: Vector2D): number;
* @returns {Vector2D}
*/
export function normalize(v: Vector2D): Vector2D;
/**
* Rotate a vector around a given centre for a given angle in radians.
*
* @param {Vector2D} v
* @param {Vector2D} centre
* @param {number} angle
*/
export function rotate(v: Vector2D, centre: Vector2D, angle: number): Vector2D;
export type Vector2D = {
x: number;
y: number;

Loading…
Cancel
Save