我不确定我在这里缺了什么。尝试通过让用户点击“旋转”按钮来使行星(即球体)旋转,但似乎无法弄清楚。我有以下代码段,该段代码可以通过用户使用鼠标与之交互来旋转球体:
document.onmousemove = function() {
if (!mouseDown) {
return;
}
var newX = event.clientX;
var newY = event.clientY;
var deltaX = newX - lastMouseX
var newRotationMatrix = mat4.create();
mat4.identity(newRotationMatrix);
mat4.rotate(newRotationMatrix, degToRad(deltaX / 10), [0, 1, 0]);
var deltaY = newY - lastMouseY;
mat4.rotate(newRotationMatrix, degToRad(deltaY / 10), [1, 0, 0]);
mat4.multiply(newRotationMatrix, planetRotationMatrix, planetRotationMatrix);
lastMouseX = newX
lastMouseY = newY;
}
这个没有问题,但我还想让行星在用户点击按钮之后自动旋转。下面是我的
onLoad
函数: window.onload = function onLoad() {
canvas = document.getElementById("gl-canvas");
initGL(canvas);
initShaders();
initBuffers();
initTexture();
initEvtHandlers();
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.enable(gl.DEPTH_TEST);
var newRotationMatrix = mat4.create();
mat4.identity(newRotationMatrix);
document.getElementById("rotate").onclick = function () {
// rotation code goes here?
}
render();
}
我的问题是:当用户点击按钮后,如何“切换”旋转?目前我尝试修改
onmousemove
函数,试图使球体在没有用户交互的情况下旋转,但这并没有起作用。更新一下,这是我添加的新
doRotate()
函数:var myRotationMatrix = mat4.create();
mat4.identity(myRotationMatrix);
doRotate = function () {
var dx = 1;
var newMatrix = mat4.create();
mat4.identity(newMatrix);
mat4.rotate(newMatrix, degToRad(dx / 10), [0, 1, 0]);
mat4.multiply(newMatrix, myRotationMatrix);
requestAnimFrame(doRotate);
}
当前这个功能对我来说不可用。当点击按钮时,应该调用此函数,切换旋转。
更新:
有一个类似的示例,请参见此页面。我正在尝试在用户点击相关按钮后自动使球体旋转。这显然不在链接的演示中 - 这只是为了澄清目的。
更新2:
我已经解决了问题。请参阅下面的答案获取详细信息。
requestAnimationFrame
来创建某种动画循环,并且每次在循环中都稍微旋转一下行星。示例。 - gman