Game Development 8 min read

2D Vector Rotation: Theory and Implementation

Rotating a 2‑D vector is performed by multiplying it with the matrix [[cos θ, ‑sin θ],[sin θ, cos θ]], yielding the new coordinates (x cos θ ‑ y sin θ, x sin θ + y cos θ); a short JavaScript function implements this, turning [3,2] into [‑2,3] for a 90° counter‑clockwise rotation and also rotates the basis vectors.

DaTaobao Tech
DaTaobao Tech
DaTaobao Tech
2D Vector Rotation: Theory and Implementation

Vector operations are the mathematical foundation of computer graphics; rotating a vector in 2D is a common operation.

In front‑end projects the CSS rotate function is used, but the underlying principle is the same.

A 2‑D vector is an array [x, y]. Rotating it by an angle θ (radians) yields a new vector: [x·cosθ ‑ y·sinθ, x·sinθ + y·cosθ] The rotation can be expressed with a 2×2 matrix: [[cosθ, ‑sinθ], [sinθ, cosθ]] Multiplying this matrix by the original vector produces the rotated vector.

Example code (JavaScript):

/**
 * @param {[x, y]} v original vector
 * @param {number} rad rotation angle in radians
 * @return {[x, y]} rotated vector
 */
function rotate(v, rad) {
  const c = Math.cos(rad);
  const s = Math.sin(rad);
  const [x, y] = v;
  return [
      x * c + y * -s,
      x * s + y * c
  ];
}

Using this function, a vector v = [3, 2] rotated 90° counter‑clockwise (θ = π/2) becomes [-2, 3].

The same matrix approach can be used to rotate basis vectors i = (1,0) and j = (0,1), yielding coordinates (cosθ, sinθ) and (‑sinθ, cosθ) respectively.

A demo visualises a tree built with vector rotation.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

math2DmatrixrotationVector
DaTaobao Tech
Written by

DaTaobao Tech

Official account of DaTaobao Technology

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.