我有一个网格,我在其中放置一个对象,我想围绕一个固定的单元格(cell3)旋转。该对象包含坐标,如:
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
},
}
}
输出:
我想围绕cell3旋转此对象,例如使用x:2,y:2,不使用某种(基本)三角函数对每个单元格位置进行硬编码。我意识到我必须检查每个细胞与细胞3的距离以及方向。但是我不知道如何进行计算,因为我对三角学不太了解。新的活动对象将是:
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
},
}
}
输出:
答案 0 :(得分:3)
一些基本想法
找到了一些数学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>');