我试图旋转移动的物体,但它围绕坐标系的中心旋转。如何让它在移动时绕着自己旋转?密码是:
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/