我有一个网格,我在其中放置一个对象,我想围绕一个固定的单元格(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
},
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
我想围绕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
},
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
一些基本想法
\n\n一些数学可以在这里找到。
\n\nfunction Point(x, y) {\r\n this.x = x;\r\n this.y = y;\r\n}\r\n\r\nPoint.prototype.rotateCW = function (c) {\r\n // x\' = x cos phi + y sin phi \\ formula with pivot at (0, 0)\r\n // y\' = -x sin phi + y cos phi /\r\n // phi = 90\xc2\xb0 insert phi\r\n // cos 90\xc2\xb0 = 0 sin 90\xc2\xb0 = 1 calculate cos and sin \r\n // x\' = y \\ formula with pivot at (0, 0)\r\n // y\' = -x /\r\n // x\' = (cy - y) + cx \\ formula with different pivot needs correction \r\n // y\' = -(cx - x) + cy /\r\n // y\' = -cx + x + cy /\r\n return new Point(\r\n c.x + c.y - this.y,\r\n c.y - c.x + this.x\r\n );\r\n}\r\n\r\nPoint.prototype.rotateCCW = function (c) {\r\n // source: https://en.wikipedia.org/wiki/Rotation_(mathematics)#Two_dimensions\r\n // x\' = x cos phi + y sin phi \\ formula with pivot at (0, 0)\r\n // y\' = -x sin phi + y cos phi /\r\n // phi = -90\xc2\xb0\r\n // cos -90\xc2\xb0 = 0 sin -90\xc2\xb0 = -1\r\n // x\' = -y \\ formula with pivot at (0, 0)\r\n // y\' = x /\r\n // x\' = -(cy - y) + cx \\ formula with different pivot needs correction \r\n // x\' = -cy + y + cx /\r\n // y\' = (cx - x) + cy /\r\n return new Point(\r\n c.x - c.y + this.y,\r\n c.y + c.x - this.x\r\n );\r\n}\r\n\r\nvar activeObject = {\r\n coords: {\r\n cell1: new Point(0, 0),\r\n cell2: new Point(1, 1),\r\n cell3: new Point(2, 2),\r\n cell4: new Point(2, 3),\r\n cell5: new Point(3, 3),\r\n }\r\n },\r\n pivot = new Point(2, 2),\r\n rotated = { coords: {} };\r\n\r\nObject.keys(activeObject.coords).forEach(function (k) {\r\n rotated.coords[k] = activeObject.coords[k].rotateCW(pivot);\r\n});\r\n\r\ndocument.write(\'<pre>\' + JSON.stringify(rotated, 0, 4) + \'</pre>\');Run Code Online (Sandbox Code Playgroud)\r\n