EN
JavaScript - rotate localized vector 2D to right direction (clockwise direction)
8
points
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:
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) ←