I'm using WebGL with javascript in order to make a square rotate around one of its vertices, with the option to change the rotation vertex if some keys are pressed.
The problem is that whenever there is a change of vertices, it keeps the center of rotation at the center of the canvas. I'd like to update their positions on the vertex swap, allowing the square to "walk" on the screen.
I'm using the cuon-matrix, cuon-utils, webgl-utils and webgl-debug libraries.
draw() function, that set the rotation matrix, pass the rotation matrix to the vertex shader, clear and draw the rectangle
function draw (gl, n, currentAngle, currentIndex, modelMatrix, u_ModelMatrix) {
modelMatrix.setRotate(-currentAngle, 0, 0, 1);
modelMatrix.translate(currentIndex[0], currentIndex[1], currentIndex[2]);
gl.uniformMatrix4fv(u_ModelMatrix, false, modelMatrix.elements);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, n);
};
Animation loop
var vertices = new Float32Array([
-0.3, -0.3, 0.3,
-0.3, 0.3, 0.3,
-0.3, -0.3, 0.3,
0.3, -0.3, 0.3,
]);
var n = vertices.length / 2;
const indexCoord = {
'r': [vertices[0], vertices[1], vertices[2]],
'g': [vertices[3], vertices[4], vertices[5]],
'b': [vertices[6], vertices[7], vertices[8]],
'w': [vertices[9], vertices[10], vertices[11]]
};
var currentAngle = 0.0;
var currentIndex = indexCoord['r'];
document.addEventListener("keydown", (e) => {
if (e.key === 'r' ||
e.key === 'g' ||
e.key === 'b' ||
e.key === 'w') {
currentIndex = indexCoord[e.key];
}
});
var modelMatrix = new Matrix4();
var runanimation = function() {
currentAngle = updateAngle(currentAngle);
draw(gl, n, currentAngle, currentIndex, modelMatrix, u_ModelMatrix);
requestAnimationFrame(runanimation);
};
runanimation();
Does anyone know how I can change my code so that the current positions of the vertices are maintained when changing the rotation reference vertex?