我的draw()
课程中有一个Triangle
方法,如下所示:
protected void draw() {
mPositionHandle = GLES20.glGetAttribLocation(mProgram, "a_Position");
mColorHandle = GLES20.glGetAttribLocation(mProgram, "a_Color");
GLES20.glUseProgram(mProgram);
vertexBuffer.position(0);
GLES20.glVertexAttribPointer(mPositionHandle, 2, GLES20.GL_FLOAT, false,
0, vertexBuffer);
GLES20.glEnableVertexAttribArray(mPositionHandle);
vertexBuffer.position(6);
GLES20.glVertexAttribPointer(mColorHandle, 4, GLES20.GL_FLOAT, false,
0, vertexBuffer); // NOTE: A stride of 0 since the data is packed.
GLES20.glEnableVertexAttribArray(mColorHandle);
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3);
GLES20.glDisableVertexAttribArray(mPositionHandle);
GLES20.glDisableVertexAttribArray(mColorHandle);
}
此draw()
方法在onDrawFrame()
中不断被调用,因此我的三角形不断被绘制。我希望能够改变三角形的坐标。注意:我正在初始化我的顶点缓冲区,如下所示:
private void init() {
triangleVertexData = concat(triangleCoords, color);
ByteBuffer bb = ByteBuffer.allocateDirect(triangleVertexData.length * 4);
bb.order(ByteOrder.nativeOrder());
vertexBuffer = bb.asFloatBuffer();
vertexBuffer.put(triangleVertexData);
vertexBuffer.position(0);
}
我的triangleVertexData
格式为 {x,y,x,y,x,y,r,g,b,a,r,g,b,a,r,g,b ,a}
我的问题是,如何实施changeCoordinates(float[] p1, float[] p2, float[] p3);
方法?
到目前为止,这是我提出的:
protected void changeCoords(float[] p1, float[] p2, float[] p3) {
float[] coords = new float[] {p1[0], p1[1],
p2[0], p2[1],
p3[0], p3[1]};
triangleCoords = coords;
triangleVertexData = concat(triangleCoords, color);
vertexBuffer.clear();
vertexBuffer.put(triangleVertexData);
vertexBuffer.position(0);
}
然而这不起作用,随机时间我在put()
行上得到一个BufferOverflowException,我不明白为什么。
答案 0 :(得分:1)
我认为异常的原因是,方法changeCoords()
和draw()
不同步。请注意,您要在vertexBuffer
方法中修改draw()
:vertexBuffer.position(6);
。如果在此之后安排changeCoords()
,则会出现问题。
回复评论:
是。在vertexBuffer.put(triangleVertexData)
方法中执行语句changeCoords
之前,如果draw()
被调用,则remaining
中只会有vertexBuffer
个。{/ p>
您可以尝试以下方法之一:
vertexBuffer
方法之前将draw
的位置设置为零。可能就在..glVertexAttribPointer(mColorHandle, 4,...
陈述之后。其他事情可能我应该注意..
System.arraycopy
复制数组translateM
,scaleM
个实用程序答案 1 :(得分:0)
我不知道为什么你会试图以这种方式移动三角形。 android.opengl.Matrix
中提供的线性代数方法完全取决于您尝试做的事情。
要翻译三角形(或任何一组顶点),请:
Matrix.translateM(float[] m, int mOffset, float x, float y, float z);
并且在不同方向上拉伸顶点它是一个缩放操作:
Matrix.scaleM(float[] m, int mOffset, float x, float y, float z);
即使您要实现坐标更改方法,也只能按照指定triangleVertexData
的方式指定顶点/颜色。