在opengl中翻译不正确

时间:2016-01-03 21:07:58

标签: android c++ opengl-es

我在android中使用opengl进行2D游戏。我有一个方形纹理精灵,我打算用它作为一个弹跳球。 我面临的问题是关于精灵的翻译。我使用单个模型矩阵作为我的顶点着色器的统一。我在渲染每个精灵之前更新该矩阵。这是正确的方法吗?

我想通过使用重力效果使球加速,但它只能以恒定的速度进行平移。

这是精灵类的更新功能: -

ArrayIndexOutOfBoundsException

我的顶点着色器: -

    public Ball(int textureID) {
    texture = textureID;
    //Stores location of the center of the ball
    location = new Vector(300,350);
    //The velocity of ball
    speed = new Vector(0, 0);
    //gravity acceleration
    accel = new Vector(0, 2);
    //Geometry of ball
    rect = new Geometry.Rectangle(new Geometry.Point(location.getI() - RADIUS,location.getJ() - RADIUS, 0), 2*RADIUS, 2*RADIUS);
    //Builder class to create vertex coordinates
    builder = new ObjectBuilder(ObjectBuilder.RECTANGLE2D, true);
    builder.generateData(rect, 0);
    //Vertex Array holds the coordinates
    vertexArray = new VertexArray(builder.vertexData);
}

public void update(float[] modelMatrix) {
    Matrix.setIdentityM(modelMatrix, 0);
    location.addVector(speed);
    Matrix.translateM(modelMatrix, 0, speed.getI(), speed.getJ(), 0);
    accel.setJ(1);
    speed.addVector(accel);
    accel.setI(-(0.3f * speed.getI()));
}

我的OnDrawFrame功能: -

uniform mat4 u_Matrix;
uniform mat4 u_ModelMatrix;

attribute vec4 a_Position;
attribute vec2 a_TextureCoordinates;

varying vec2 v_TextureCoordinates;

void main() {
v_TextureCoordinates = a_TextureCoordinates;
gl_Position = u_Matrix * u_ModelMatrix * a_Position;
}

1 个答案:

答案 0 :(得分:0)

您的更新功能错误。您按速度而不是位置翻译modelMatrix

Matrix.translateM(modelMatrix, 0, speed.getI(), speed.getJ(), 0);

您可能需要以下内容:

Matrix.translateM(modelMatrix, 0, location.getI(), location.getJ(), 0);

您的速度现在基本上起到位置的作用,每次更新都会增加:

accel.setJ(1);
speed.addVector(accel);
accel.setI(-(0.3f * speed.getI()));

speed最初为(0, 0),每次更新时都会增加accel(0, 1)始终为-(0.3f * 0) = 0#include <stdio.h> #include <stdlib.h> int compareFunc(const void *op1, const void *op2 ) { int *a, *b; a = (int*)op1; b = (int*)op2; return *a - *b; } void printUnique(int *array, int numElems) { int curPrintIndex, curCompareIndex; char alreadySeen; for (curPrintIndex=0; curPrintIndex<numElems; curPrintIndex++) { alreadySeen = 0; for (curCompareIndex=0; curCompareIndex<curPrintIndex; curCompareIndex++) { if (array[curCompareIndex] == array[curPrintIndex]) { alreadySeen = 1; break; } } if (alreadySeen == 0) printf("%d\n", array[curPrintIndex]); } } int main() { const int numItems = 100; int *array, i, lastVal; array = calloc(numItems, sizeof(int) ); for (i=0; i<numItems; i++) array[i] = rand()%numItems; printUnique(array, numItems); free(array); return 0; /* qsort(array, numItems, sizeof(int), compareFunc); printf("%d\n", array[0]); lastVal = array[0]; for (i=1; i<numItems; i++) { if (array[i] != lastVal) { lastVal = array[i]; printf("%d\n", array[i]); } } */ }

因此,您的对象以恒定的速度(0,1)移动。