2016-01-03 50 views
0

我正在android中使用opengl製作2D遊戲。我有一個方形紋理的精靈,我打算用它作爲彈跳球。 我面臨的問題是關於精靈的翻譯。我使用單個模型矩陣作爲我的頂點着色器的統一體。我在渲染每個精靈之前更新該矩陣。這是否是正確的方法?翻譯在opengl中做得不正確

我想通過使用重力效應使球加速,但它只能以恆定速度轉換。

這裏是精靈類的更新功能: -

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

回答

0

你更新功能錯誤。您可以按照速度而不是位置來翻譯您的modelMatrix

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

你可能想是這樣的:

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

你的速度basicly功能現在所在的位置,這是增加每個更新:

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

speed最初(0, 0),由accel遞增每更新一次,將始終爲(0, 1),作爲-(0.3f * 0) = 0

因此,您的對象以(0,1)的恆定速度移動。

+0

謝謝,這解決了我的問題。 btw是我翻譯對象的方法嗎? 我將這個模型矩陣傳遞給每個對象渲染前的制服。 – AribAlam

+0

我是否必須爲每個對象提供他們自己的模型矩陣,或者只是改變一個可以做到的模式 – AribAlam

+0

這是一個正確的方法。你可以每次改變一個矩陣(但是,每次改變它時,你仍然會將它作爲統一函數發送給着色器),但是我總是更喜歡爲每個對象保留一個模型矩陣。 – Reigertje