如何在OpenGL ES中移动带纹理的形状?

时间:2011-11-26 16:01:47

标签: java android opengl-es

如何移动形状?我已经尝试更改包含所有顶点但不起作用的浮动...然后我尝试了glTranslateF,但它也没有用。我做错了什么?

这是我的代码:

package com.chrypthic.android.reference;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.util.Log;

public class Square
{
final int VERTEX_SIZE = (2+2) *4;
FloatBuffer vertices;
ShortBuffer indices;

Texture texture;

GL10 gl;
Context c;

int x;
int y;
int w;
int h;

public Square(GL10 gl, Context context, int x, int y, int w, int h, String imageTexture)
{
    this.gl = gl;
    this.c = context;

    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;

    ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4 * VERTEX_SIZE);
    byteBuffer.order(ByteOrder.nativeOrder());
    vertices = byteBuffer.asFloatBuffer();
    /*vertices.put(new float[]{
        10.0f, 10.0f, 0.0f, 1.0f, //bl  
        160.0f, 10.0f, 1.0f, 1.0f, //br 
        160.0f, 160.0f, 1.0f, 0.0f, //tr    
        10.0f, 160.0f, 0.0f, 0.0f, //tl 
    });*/
    vertices.put(new float[]{
            (float)x, ((float)y+(float)h), 0.0f, 1.0f, //bl 
            ((float)x+(float)w), ((float)y+(float)h), 1.0f, 1.0f, //br  
            ((float)x+(float)w), (float)y, 1.0f, 0.0f, //tr 
            (float)x, (float)y, 0.0f, 0.0f, //tl    
        });
    vertices.flip();

    byteBuffer = ByteBuffer.allocateDirect(6 * 2);
    byteBuffer.order(ByteOrder.nativeOrder());
    indices = byteBuffer.asShortBuffer();
    indices.put(new short[]{
        0, 1, 2, 2, 3, 0
    });
    indices.flip();

    texture = new Texture(imageTexture, c, gl);
    texture.load();
}

public void draw()
{
    gl.glMatrixMode(GL10.GL_PROJECTION);
    gl.glEnable(GL10.GL_TEXTURE_2D);
    texture.bind();
    gl.glColor4f(0f, 0f, 0f, 1f);

    gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);

    vertices.position(0);
    gl.glVertexPointer(2, GL10.GL_FLOAT, VERTEX_SIZE, vertices);
    vertices.position(2);
    gl.glTexCoordPointer(2, GL10.GL_FLOAT, VERTEX_SIZE, vertices);

    gl.glDrawElements(GL10.GL_TRIANGLES, 6, GL10.GL_UNSIGNED_SHORT, indices);
}

public void update()
{
    //this doesnt work. I call the method every 10 milliseconds from a thread in another class.
    gl.glEnable(GL10.GL_TEXTURE_2D);
    gl.glTranslatef(10, y, 0);
}
}

2 个答案:

答案 0 :(得分:2)

您提供的源代码中的问题是在执行绘制操作之前需要调用glTranslatef。将矩阵模式设置为 modelview 设置平移,所有绘图将在新位置绘制。

答案 1 :(得分:1)

您提到从另一个线程调用update,但OpenGL调用仅在创建上下文的同一线程上有效。

您还应该阅读有关OpenGL转换的内容。需要付出一些努力来理解耐心。

http://glprogramming.com/red/chapter03.html