Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benbotto/f9e8ffb13efce28aebeb5d1d8d27a8c4 to your computer and use it in GitHub Desktop.
Save benbotto/f9e8ffb13efce28aebeb5d1d8d27a8c4 to your computer and use it in GitHub Desktop.
A rectangle rotating and orbiting about a point.
class Rectangle {
constructor(gl, color, width, height) {
this.gl = gl;
this.color = color;
this.width = width;
this.height = height;
// Rotation, updated before each render.
this.rotation = gl.mat2d.create();
// Orbit rotation, updated each render.
this.orbit = gl.mat2d.create();
// Translation1: The radius of orbit.
this.radiusTranslation = gl.mat2d.fromTranslation(
gl.mat2d.create(),
gl.vec2.fromValues(40, 0));
// Translation2: The center of the orbit.
this.orbitTranslation = gl.mat2d.fromTranslation(
gl.mat2d.create(),
gl.vec2.fromValues(100, 100));
}
/**
* Update the Rectangle's transformation matrix before a render.
*/
update(elapsedMs) {
// Rotate -3PI per second.
this.gl.mat2d.rotate(this.rotation, this.rotation,
-3 * Math.PI * elapsedMs / 1000);
// Orbit PI per second.
this.gl.mat2d.rotate(this.orbit, this.orbit,
Math.PI * elapsedMs / 1000);
}
/**
* Get the Rectangle's transformation matrix.
*/
getTransformation() {
// transformation = translate(P) * rotate(θ2) * translate(r, 0) * rotate(θ1)
const transformation = this.gl.mat2d.create();
this.gl.mat2d.multiply(
transformation,
this.orbitTranslation,
this.orbit);
this.gl.mat2d.multiply(
transformation,
transformation,
this.radiusTranslation);
this.gl.mat2d.multiply(
transformation,
transformation,
this.rotation);
return transformation;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment