Languages
[Edit]
EN

JavaScript - rotate localized vector 2D to right direction (clockwise direction)

8 points
Created by:
Sujay
512

In this short article, we would like to show how to rotate any localized vector 2D to the right side (90 degrees) using Javascript.

Quick solution:

function rotateRight(vector) {
  	var a = vector.a;
  	var b = vector.b;
  	return {
      	a: { x: a.y, y: -a.x },  // check: https://dirask.com/posts/jMqM0j
      	b: { x: b.y, y: -b.x }
    };
}

var vector1 = {a: {x: -1, y: 2}, b: {x: -2, y: 4}};  // vector [A1, B1] = (-1, 2) -> (-2, 4)
var vector2 = rotateRight(vector1);                  // vector [A2, B2] = ( 2, 1) -> ( 4, 2)

Rotation preview:

Localized vector 2D rotation to the right direction (clockwise direction) using JavaScript.
Localized vector 2D rotation to the right direction (clockwise direction) using JavaScript.

Practical example

// ONLINE-RUNNER:browser;

function rotateRight(vector) {
  	var a = vector.a;
  	var b = vector.b;
  	return {
      	a: { x: a.y, y: -a.x },  // check: https://dirask.com/posts/jMqM0j
      	b: { x: b.y, y: -b.x }
    };
}


// Helper methods:

function printPoint(point) {
	return '(' + point.x + ', ' + point.y + ')';
}

function printVector(name, vector) {
  	console.log(name + ': ' + printPoint(vector.a) + ' -> ' + printPoint(vector.b));
}


// Usage example:
                                  // direction:
var vector1 = {                   //   ↑
	a: {x: 0, y: 1},              // a = beginning point
  	b: {x: 0, y: 2}               // b = ending point (arrow/head)
};          

var vector2 = rotateRight(vector1);   //   →
var vector3 = rotateRight(vector2);   //   ↓
var vector4 = rotateRight(vector3);   //   ←

printVector('vector1', vector1);  // ( 0,  1) -> ( 0,  2)  ↑
printVector('vector2', vector2);  // ( 1,  0) -> ( 2,  0)  →
printVector('vector3', vector3);  // ( 0, -1) -> ( 0, -2)  ↓
printVector('vector4', vector4);  // (-1,  0) -> (-2,  0)  ←

See also

  1. JavaScript - rotate localized vector 2D to left direction (counterclockwise direction)

  2. JavaScript - rotate vector 2D to right direction (clockwise direction)

  3. JavaScript - rotate vector 2D to left direction (counterclockwise direction)

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join