如果您转到以下链接,您会看到一个非常酷的 Javascript 模拟立方体,它根据您的鼠标位置旋转。
模拟:这里。
如果您查看立方体旋转脚本的源代码,您将看到:
<script type="text/javascript">
/* I wrote this script in a few minutes just for fun. It's not made to win any
competition. */
var dimension = 1, a = 0, b = 0, i = 27;
while (i--) document.write('<b id="l' + i + '">+</b>');
function f()
{
i = 0;
for (x = -dimension; x <= dimension; x += dimension)
for (y = -dimension; y <= dimension; y += dimension)
for (z = -dimension; z <= dimension; z += dimension)
{
u = x;
v = y;
w = z;
u2 = u * Math.cos(a) - v * Math.sin(a);
v2 = u * Math.sin(a) + v * Math.cos(a);
w2 = w;
u = u2; v = v2; w = w2;
u2 = u;
v2 = v * Math.cos(b) - w * Math.sin(b);
w2 = v * Math.sin(b) + w * Math.cos(b);
u = u2; v = v2; w = w2;
var c = Math.round((w + 2) * 70);
if (c < 0) c = 0;
if (c > 255) c = 255;
s = document.getElementById('l' + i).style;
s.left = 300 + u * (w + 2) * 50;
s.top = 300 + v * (w + 2) * 50;
s.color = 'rgb(' + c + ', ' + c + ', 0)';
s.fontSize = (w + 2) * 16 + 'px';
/* The Digg users missed depth sort, so here it is. */
s.zIndex = Math.round((w + 2) * 10);
i++;
}
}
/* Using a timer instead of the onmousemove handler wastes CPU time but makes
the animation much smoother. */
setInterval('f()', 17);
</script>
我看了好几遍,还是不明白立方体的点是怎么计算的。这是使用“欧拉旋转”吗?我遇到的一个大问题是使用对我来说毫无意义的单字母变量名。
有必要的数学知识的人会帮助解释在这个模拟中旋转立方体背后的数学是如何工作的吗?我想做类似的事情,但是在计算积分位置时,我有点迷茫。