我正在尝试使用gl.drawArrays + gl.TRIANGLES
绘制2个三角形,但这根本行不通(顺便说一句,我正在使用cocos2d-js)。
这就是我所做的。
添加顶点的第一个代码。
addVertex:function(x, y) {
this._vertexCount += 1;
this._vertexArray.push(cc.p(x, y));
this.updateVertexArray();
}
updateVertexArray:function() {
this._vertices = new Array(this._vertexCount * 2);
this._uvs = new Array(this._vertexCount * 2);
var width = this.getContentSize().width;
var height = this.getContentSize().height;
for (var i = 0; i < this._vertexCount; i ++) {
var vertex = this._vertexArray[i];
this._vertices[i * 2 + 0] = width * vertex.x;
this._vertices[i * 2 + 1] = height * vertex.y;
this._uvs[i * 2 + 0] = vertex.x;
this._uvs[i * 2 + 1] = 1 - vertex.y;
}
this._vertexView = new Float32Array(this._vertices);
this._uvView = new Float32Array(this._uvs);
gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, this._vertexView, gl.DYNAMIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer);
gl.bufferData(gl.ARRAY_BUFFER, this._uvView, gl.DYNAMIC_DRAW);
}
绘制部分:
draw:function () {
gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION);
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer);
gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_TEX_COORDS);
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLES, 0, this._vertexCount);
}
然后它可以与一个三角形配合使用:
customGLNode.addVertex(cc.p(0.0, 0.0));
customGLNode.addVertex(cc.p(0.5, 0.0));
customGLNode.addVertex(cc.p(0.5, 0.5));
结果是:
它与另一个三角形也可以正常工作
customGLNode.addVertex(cc.p(0.6, 0.6));
customGLNode.addVertex(cc.p(1.0, 0.6));
customGLNode.addVertex(cc.p(1.0, 1.0));
结果是:
但是当我尝试将两个三角形绘制在一起时:
customGLNode.addVertex(cc.p(0.0, 0.0));
customGLNode.addVertex(cc.p(0.5, 0.0));
customGLNode.addVertex(cc.p(0.5, 0.5));
customGLNode.addVertex(cc.p(0.6, 0.6));
customGLNode.addVertex(cc.p(1.0, 0.6));
customGLNode.addVertex(cc.p(1.0, 1.0));
什么也没显示,我的错误是:
GL ERROR :GL_INVALID_OPERATION : glDrawArrays: attempt to access out of range vertices in attribute 1
但是看来顶点数组都很好:
每个顶点每个属性(位置/ uv)使用2个浮点数,
现在我有2个三角形
=> 6个顶点
=>位置数组的12个浮点数
=> uv数组有12个浮点数
任何建议将不胜感激,谢谢:)