I have a grid at which I place an object I want to rotate right around a fixed cell (cell3). The object contains coordinates, like:
activeObject = {
coords: {
cell1: {
x: 0,
y: 0
},
cell2: {
x: 1,
y: 1
},
cell3: {
x: 2,
y: 2
},
cell4: {
x: 2,
y: 3
},
cell5: {
x: 3,
y: 3
},
}
}
Output:
I want to rotate this object around cell3 e.g. using x: 2, y: 2 without hard coding each cell position using some kind of (basic) trigonometry. I realize that I have to check how far is each cell from cell3, and the orientation. But I don't know how to do the calculation as I am not so good with trigonometry. The new active object would be:
activeObject = {
coords: {
cell1: {
x: 4,
y: 0
},
cell2: {
x: 4,
y: 1
},
cell3: {
x: 2,
y: 2
},
cell4: {
x: 1,
y: 2
},
cell5: {
x: 1,
y: 3
},
}
}
Output:
Some basic thoughts
Some Math is found here.
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.rotateCW = function (c) {
// x' = x cos phi + y sin phi \ formula with pivot at (0, 0)
// y' = -x sin phi + y cos phi /
// phi = 90° insert phi
// cos 90° = 0 sin 90° = 1 calculate cos and sin
// x' = y \ formula with pivot at (0, 0)
// y' = -x /
// x' = (cy - y) + cx \ formula with different pivot needs correction
// y' = -(cx - x) + cy /
// y' = -cx + x + cy /
return new Point(
c.x + c.y - this.y,
c.y - c.x + this.x
);
}
Point.prototype.rotateCCW = function (c) {
// source: https://en.wikipedia.org/wiki/Rotation_(mathematics)#Two_dimensions
// x' = x cos phi + y sin phi \ formula with pivot at (0, 0)
// y' = -x sin phi + y cos phi /
// phi = -90°
// cos -90° = 0 sin -90° = -1
// x' = -y \ formula with pivot at (0, 0)
// y' = x /
// x' = -(cy - y) + cx \ formula with different pivot needs correction
// x' = -cy + y + cx /
// y' = (cx - x) + cy /
return new Point(
c.x - c.y + this.y,
c.y + c.x - this.x
);
}
var activeObject = {
coords: {
cell1: new Point(0, 0),
cell2: new Point(1, 1),
cell3: new Point(2, 2),
cell4: new Point(2, 3),
cell5: new Point(3, 3),
}
},
pivot = new Point(2, 2),
rotated = { coords: {} };
Object.keys(activeObject.coords).forEach(function (k) {
rotated.coords[k] = activeObject.coords[k].rotateCW(pivot);
});
document.write('<pre>' + JSON.stringify(rotated, 0, 4) + '</pre>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With