简体   繁体   English

Android OpenGL ES 2.0:围绕特定点旋转对象

[英]Android OpenGL ES 2.0: rotate an object around a specific point

I want to rotate an element around a specific point defined by me and dynamically changed. 我想围绕由我定义并动态更改的特定点旋转元素。

I am orientating myself at the guidelines from the google developers site . 我正在按照google开发人员网站上的指南进行操作。

My first approach is this: 我的第一种方法是:

scratch = new float[16];
Matrix.setIdentityM(mRotationMatrix, 0);
Matrix.setRotateM(mRotationMatrix, 0, angle, 0, 0, 1f);
Matrix.multiplyMM(scratch, 0, mMVPMatrix, 0, mRotationMatrix, 0);
element.draw(scratch);

This rotates the object around the center of the screen. 这将围绕屏幕中心旋转对象。

What do I have to add/change to make the object rotate around some other point? 我必须添加/更改什么才能使对象绕其他点旋转?

Add a translation operation. 添加翻译操作。

Grafika's Sprite2d class provides an example: Grafika的Sprite2d类提供了一个示例:

/**
 * Re-computes mModelViewMatrix, based on the current values for rotation, scale, and
 * translation.
 */
private void recomputeMatrix() {
    float[] modelView = mModelViewMatrix;

    Matrix.setIdentityM(modelView, 0);
    Matrix.translateM(modelView, 0, mPosX, mPosY, 0.0f);
    if (mAngle != 0.0f) {
        Matrix.rotateM(modelView, 0, mAngle, 0.0f, 0.0f, 1.0f);
    }
    Matrix.scaleM(modelView, 0, mScaleX, mScaleY, 1.0f);
    mMatrixReady = true;
}

This positions the object, then rotates it around the center of the object. 这将放置对象,然后将其绕对象中心旋转。

You need to translate the matrix in the reverse direction of the point first, then rotate and then translate it back. 您需要先沿点的反方向平移矩阵,然后旋转然后再将其平移回去。 Look at it as if the rotation is always rotating around the center of the world, and the translation moves the center of the world. 看起来好像旋转总是绕着世界的中心旋转,而平移则移动着世界的中心。

Something like this (untested): 像这样(未经测试):

scratch = new float[16];
Matrix.setIdentityM(mRotationMatrix, 0);
Matrix.translateM(mRotationMatrix, 0, -x, -y, -z);
Matrix.rotateM(mRotationMatrix, 0, angle, 0, 0, 1f);
Matrix.translateM(mRotationMatrix, 0, x, y, z);
Matrix.multiplyMM(scratch, 0, mMVPMatrix, 0, mRotationMatrix, 0);
element.draw(scratch);

The x , y and z values need to be calculated as the delta between the current position of the object in the world and the position of the point you want to rotate around. 需要将xyz值计算为对象在世界上的当前位置与要旋转的点的位置之间的增量。 You need to do that calculation yourself, but that's pretty trivial. 您需要自己进行计算,但这很简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM