[英]Android OpenGL ES rotate 3D object with touch event
This is an Android application.这是一个安卓应用程序。 I want to rotate a sphere with touch event using Matrix in OpenGLES 2.0.我想在 OpenGLES 2.0 中使用 Matrix 旋转带有触摸事件的球体。 However the angle is not right.不过角度不对。 It seems like the rotate is not stable.好像旋转不稳定。 I want to rotate only x when I touch horizontally, and rotate only y when I touch vertically.我想水平触摸时只旋转 x,垂直触摸时只旋转 y。 But in fact, when I touch horizontally it rotate x and y, so did when I touch vertically... Something wrong with the calculation of rotate anglex and angley or the Matrix set up?但实际上,当我水平触摸时它会旋转 x 和 y,当我垂直触摸时也是如此......旋转角度x 和角度的计算或矩阵设置有问题吗? Here is the touch event:这是触摸事件:
public boolean onTouchEvent(MotionEvent e) {
float x = e.getX();
float y = e.getY();
switch (e.getAction()) {
case MotionEvent.ACTION_MOVE:
float dx = x - mPreviousX;
float dy = y - mPreviousY;
mRenderer.setAngleX(mRenderer.getAngleX() + (dx * TOUCH_SCALE_FACTOR));
mRenderer.setAngleY(mRenderer.getAngleY() - (dy * TOUCH_SCALE_FACTOR));
requestRender();
}
mPreviousX = x;
mPreviousY = y;
return true;
}
This is the Matrix set up:这是矩阵设置:
public void onDrawFrame(GL10 unused) {
// Draw background color
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
//set up the matrix
float [] mTempMatrix = new float[16];
Matrix.setIdentityM(mModelMatrix, 0); // initialize to model matrix
Matrix.setIdentityM(mTranslateMatrix,0);
Matrix.translateM(mTranslateMatrix, 0, 0.0f, 0.0f, 0.0f);
mTempMatrix = mModelMatrix.clone();
Matrix.multiplyMM(mModelMatrix,0,mTempMatrix,0,mTranslateMatrix,0);
Matrix.setIdentityM(mRotationMatrix,0);
Matrix.rotateM(mRotationMatrix, 0, mAngleX, 0,1,0);
Matrix.rotateM(mRotationMatrix, 0, mAngleY, 1,0,0);
mTempMatrix = mModelMatrix.clone();
Matrix.multiplyMM(mModelMatrix,0,mTempMatrix,0,mRotationMatrix,0);
Matrix.setIdentityM(mScaleMatrix,0);
Matrix.scaleM(mScaleMatrix,0, 1f, 1f, 1f);
mTempMatrix = mModelMatrix.clone();
Matrix.multiplyMM(mModelMatrix,0,mTempMatrix,0,mScaleMatrix,0);
Matrix.setLookAtM(mViewMatrix, 0,
mLocation.x,mLocation.y,mLocation.z,
mTarget.x,mTarget.y,mTarget.z,
mUp.x,mUp.y,mUp.z);//camera
mTempMatrix = mViewMatrix.clone();
Matrix.multiplyMM(mViewMatrix, 0, mTempMatrix,0,mModelMatrix,0);
Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mViewMatrix, 0);
mSphere.draw(mMVPMatrix);
}
It seems to me that since you use在我看来,既然你使用
mRenderer.setAngleX(mRenderer.getAngleX() + (dx * TOUCH_SCALE_FACTOR));
Even if dx
is 0, any previous angle (through mRenderer.getAngleX()
) will be re-applied in the next iteration.即使dx
为 0,任何先前的角度(通过mRenderer.getAngleX()
)将在下一次迭代中重新应用。 Let dx
alone modify mAngleX
instead (and do the same for mAngleY
of course):让dx
单独修改mAngleX
(当然对mAngleY
也这样做):
mRenderer.mAngleX += dx * TOUCH_SCALE_FACTOR;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.