12:01
Цветной куб WebGL — Лисья нора
§ Куб, который вращался
Суть такова. Есть набор вершин и есть набор цветов к ним. А также вращение вокруг своей оси.
§ Инициализация
init(gl)
{
this.shader = this.loadShader();
const vertices = [
// Передняя грань
-1.0, -1.0, 1.0, // 0
1.0, -1.0, 1.0, // 1
1.0, 1.0, 1.0, // 2
-1.0, 1.0, 1.0, // 3
// Задняя грань
-1.0, -1.0, -1.0, // 4
-1.0, 1.0, -1.0, // 5
1.0, 1.0, -1.0, // 6
1.0, -1.0, -1.0, // 7
// Верхняя грань
-1.0, 1.0, -1.0, // 8
-1.0, 1.0, 1.0, // 9
1.0, 1.0, 1.0, // 10
1.0, 1.0, -1.0, // 11
// Нижняя грань
-1.0, -1.0, -1.0, // 12
1.0, -1.0, -1.0, // 13
1.0, -1.0, 1.0, // 14
-1.0, -1.0, 1.0, // 15
// Правая грань
1.0, -1.0, -1.0, // 16
1.0, 1.0, -1.0, // 17
1.0, 1.0, 1.0, // 18
1.0, -1.0, 1.0, // 19
// Левая грань
-1.0, -1.0, -1.0, // 20
-1.0, -1.0, 1.0, // 21
-1.0, 1.0, 1.0, // 22
-1.0, 1.0, -1.0, // 23
];
const colors = [
[1.0, 1.0, 1.0, 1.0], // Front face: white
[1.0, 0.0, 0.0, 1.0], // Back face: red
[0.0, 1.0, 0.0, 1.0], // Top face: green
[0.0, 0.0, 1.0, 1.0], // Bottom face: blue
[0.0, 1.0, 1.0, 1.0], // Right face: cyan
[1.0, 0.0, 1.0, 1.0], // Left face: purple
];
const indicies = [
0, 1, 2, 0, 2, 3, // front
4, 5, 6, 4, 6, 7, // back
8, 9, 10, 8, 10, 11, // top
12, 13, 14, 12, 14, 15, // bottom
16, 17, 18, 16, 18, 19, // right
20, 21, 22, 20, 22, 23, // left
];
let newColors = [];
for (let i = 0; i < 6; i++) {
for (let j = 0; j < 4; j++) {
newColors = newColors.concat(colors[i]);
}
}
// Инициалиазация буферов и назначение вершинного шейдера
this.setAttribute(this.shader, this.createBuffer(vertices), 'aPosition', 3);
this.setAttribute(this.shader, this.createBuffer(newColors), 'aColor', 4);
this.bindIndicies(this.createIndicies(indicies));
// Для вращения
this._mx = 0; this._my = 0; this._mz = 0;
}§ Вращение куба в цикле
loop(gl)
{
this.cls(0, 0, 0);
this.camera = this.dot
(
this.matRotZ(this._mz),
this.matRotY(this._my),
this.matRotX(this._mx),
this.matTr(0, 0, -3),
);
this.updateCamera(this.shader);
gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_SHORT, 0);
this._mx -= 0.01;
this._my -= 0.02;
this._mz -= 0.03;
}