javascript - 当我尝试绕轴和中心旋转时,对象在屏幕外平移
问题描述
我正在尝试围绕它自己的 3 轴旋转一个立方体,并使其绕屏幕中心运行。这两种转换单独工作,但是当我一起运行它们时,立方体慢慢地移出屏幕。
function loop(timeNow) {
//calculate time difference
timeDelta = timeNow - timeLast;
timeLast = timeNow;
// background
ctx.fillRect(0, 0, w, h);
// c is the centre of the cube
// rotate along z axis
let angle = timeDelta * 0.001 * SPEED_Z * Math.PI * 2;
for (let v of vertices) {
let dx = v.x - c.x;
let dy = v.y - c.y;
let x = dx * Math.cos(angle) - dy * Math.sin(angle);
let y = dx * Math.sin(angle) + dy * Math.cos(angle);
v.x = x + c.x;
v.y = y + c.y;
}
// rotate along x axis
angle = timeDelta * 0.001 * SPEED_X * Math.PI * 2;
for (let v of vertices) {
let dz = v.z - c.z;
let dy = v.y - c.y;
let z = dy * Math.sin(angle) + dz * Math.cos(angle);
let y = dy * Math.cos(angle) - dz * Math.sin(angle);
v.z = z + c.z;
v.y = y + c.y;
}
// rotate along y axis
angle = timeDelta * 0.001 * SPEED_Y * Math.PI * 2;
for (let v of vertices) {
let dz = v.z - c.z;
let dx = v.x - c.x;
let z = dz * Math.cos(angle) - dx * Math.sin(angle);
let x = dz * Math.sin(angle) + dx * Math.cos(angle);
v.z = z + c.z;
v.x = x + c.x;
}
// centre is the centre of the page
// rotating around the centre of the page
let theta = Math.PI * 2 * timeDelta * 0.001 * 0.5;
for (let v of vertices) {
let dx = v.x - centre.x;
let dy = v.y - centre.y;
let x = dx * Math.cos(theta) - dy * Math.sin(theta);
let y = dx * Math.sin(theta) + dy * Math.cos(theta);
v.x = centre.x + x;
v.y = centre.y + y;
}
// draw each edge
for (let edge of edges) {
ctx.beginPath();
ctx.moveTo(vertices[edge[0]].x, vertices[edge[0]].y);
ctx.lineTo(vertices[edge[1]].x, vertices[edge[1]].y);
ctx.stroke();
}
// call next frame
requestAnimationFrame(loop);
}
我曾尝试阅读仿射变换并将它们组合起来,但我无法将理论转化为这段代码。任何帮助,将不胜感激。
解决方案
推荐阅读
- java - 在后台使用 Netty 与 Tomcat 时 Spring webFlux 的差异
- ionic-framework - 如何调整离子复选框的高度和宽度?
- ssis - 找不到配置文件
- r - 更改现有 Df 中的语言编码(不在导入时)
- python - 使用python从json文件中删除最后一个逗号
- excel - 当在合并单元格中找到值时,.FindNext 不会“环绕”
- c# - 在项目之间传递信息的快捷方式
- machine-learning - 我们如何决定卷积自动编码器中的卷积层数?
- authentication - 如何停止 Sitecore 重定向到某些 URL 的登录页面
- r - 无法使用 Rstudio 写入 csv 文件