gpt4 book ai didi

javascript - 如何根据中心单元旋转对象

转载 作者:搜寻专家 更新时间:2023-11-01 04:23:30 27 4
gpt4 key购买 nike

我有一个网格,我在其中放置了一个要围绕固定单元格 (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 而无需使用某种(基本)三 Angular 函数对每个单元格位置进行硬编码。我意识到我必须检查每个单元格与单元格 3 的距离以及方向。但我不知道如何计算,因为我不太擅长三 Angular 学。新的事件对象将是:

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
},
}
}

输出:

enter image description here

最佳答案

一些基本思想

  • 如果枢轴不是原点,则必须对转换应用一些修正。
  • 如果点在 (1, 2),则绕原点旋转
    • 顺时针 90°:变为 (2, -1)
    • 逆时针 90°:变成 (-2, 1)
  • 点(x, y)的结论
    • 顺时针 90°:变为 (y, -x)
    • 逆时针 90°:变为 (-y, x)
  • 至少对枢轴应用修正

找到了一些数学 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>');

关于javascript - 如何根据中心单元旋转对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34878417/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com