【问题标题】:translation done incorrectly in opengl在opengl中翻译不正确
【发布时间】:2016-01-05 01:07:34
【问题描述】:

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

我想通过重力效果让球加速,但它只能以恒定速度平移。

这里是精灵类的更新函数:-

    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()));
}

我的顶点着色器:-

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;
}

我的 OnDrawFrame 函数:-

public void onDrawFrame(GL10 gl) {    
   textureShaderProgram.useProgram();
   ball.update(modelMatrix);
   textureShaderProgram.setUniforms(projectionMatrix, modelMatrix);
   ball.bindData(textureShaderProgram);
   ball.render();
}

【问题讨论】:

    标签: android c++ opengl-es


    【解决方案1】:

    您的更新功能错误。您通过速度而不是位置来翻译您的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

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

    【讨论】:

    • 谢谢,这解决了我的问题。顺便说一句,我翻译对象的方法对吗?在每次渲染对象之前,我都会将此模型矩阵传递给制服。
    • 我必须给每个对象自己的模型矩阵还是只改变一个就可以了
    • 这是正确的做法。您可以每次只更改一个矩阵(但是,每次更改时您仍然需要将其作为统一发送到着色器),但是我总是更喜欢为每个对象保留一个模型矩阵。
    猜你喜欢
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    相关资源
    最近更新 更多