android - OpenGL ES 2.0 : Rotating object around itself on Android

标签 android opengl-es

我试图旋转移动的物体,但它围绕坐标系的中心旋转。如何让它在移动时绕着自己旋转?密码是:

Matrix.translateM(mMMatrix, 0, 0, -y, 0);
Matrix.setRotateM(mMMatrix, 0, mAngle, 0, 0, 1.0f);
y += speed;
Matrix.translateM(mMMatrix, 0, 0, y, 0); 

最佳答案

不要使用 View 矩阵来旋转对象,该矩阵用作所有场景的相机,要变换对象,您应该使用模型矩阵。如果要围绕自身中心旋转,可以使用以下方法:

public void transform(float[] mModelMatrix) {
    Matrix.setIdentityM(mModelMatrix, 0);
    Matrix.translateM(mModelMatrix, 0, 0, y, 0);
    Matrix.rotateM(mModelMatrix, 0, mAngle, 0.0f, 0.0f, 1.0f); 
}

不要忘记使用单位矩阵来重置每个循环中的转换。

我认为您的代码很糟糕。在应用任何转换之前,您应该更新“y”的值。

public void onDrawFrame(GL10 gl) {
    ...
    y += speed;
    transform(mModelMatrix);
    updateMVP(mModelMatrix, mViewMatrix, mProjectionMatrix, mMVPMatrix);
    renderObject(mMVPMatrix);
    ...
}

updateMVP 方法,将结合模型、 View 和投影矩阵:

private void updateMVP( 
        float[] mModelMatrix, 
        float[] mViewMatrix, 
        float[] mProjectionMatrix,
        float[] mMVPMatrix) {

    // combine the model with the view matrix
    Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);

    // combine the model-view with the projection matrix
    Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix,   0);
}

最后是 render 方法,将执行着色器来绘制对象:

public void renderObject(float[] mMVPMatrix) {

    GLES20.glUseProgram(mProgram);

    ...

    // Pass the MVP data into the shader
    GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix, 0);

    // Draw the shape
    GLES20.glDrawElements (...);
}

希望对您有所帮助。

关于android - OpenGL ES 2.0 : Rotating object around itself on Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10551225/

相关文章:

android - 在android中录制后将音频文件发送到服务器

javascript - iOS 和安卓 webview : how to close webview and go back to App?

android - 启动启动时终止所有其他先前的 Activity

android - 无法在 Widget 中更新 Button 的文本

android - 将数据从一个纹理复制到另一个 - opengl

android - 应该使用什么作为 url_launcher 中的 url 来使 flutter 应用程序打开设备上的内置摄像头?

Android MediaCodec 输出格式 : GLES External Texture (YUV/NV12) to GLES Texture (RGB)

opengl - 片段着色器 GLSL 中未使用的可变变量 - 它们会伤害性能吗

ios - OpenGL ES 2/iOS GLKit 的设计建议

ios - 如何在 ios 中进行色度键控以使用 Swift 处理视频文件