Monday, April 25, 2016

Making a Sphere Rotate in WebGL

Leave a Comment

Not sure what I'm missing here. Trying to make a planet (i.e. sphere) rotate by having the user click on a 'Rotate' button, but can't seem to figure it out. I do have the following segment which rotates the sphere by way of user interaction with the mouse:

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

This one works fine, but I also want to make the planet rotate automatically after the user clicks the button. Here is my onLoad function:

    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();  } 

My question is: How can I 'toggle' the rotation after the user clicks the button? So far what I've tried is modify the onmousemove function in an attempt to make the sphere rotate without user interaction, but that's not working.

As an update, here is a new doRotate() function I added:

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); } 

Which is currently not working for me. This function is supposed to be called when the button is clicked, toggling the rotation.

Update:

For a similar demo, please see this page. What I'm trying to do is make the sphere rotate automatically after the user clicks the relevant button. This is obviously not in the demo linked--that's only for clarification purposes.

Update 2:

I've since figured it out. Please see my answer below for details.

0 Answers

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment