Android OpenGL ES通过触摸事件旋转3D对象

时间:2016-04-20 10:11:51

标签: android opengl-es

这是一个Android应用程序。我想使用OpenGLES 2.0中的Matrix旋转带触摸事件的球体。但是角度不对。看起来旋转不稳定。我想在水平触摸时仅旋转x,在垂直触摸时仅旋转y。但实际上,当我水平触摸时,它会旋转x和y,当我垂直触摸时也是如此...旋转角度和角度或矩阵设置的计算有问题吗? 这是触摸事件:

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

这是Matrix设置:

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

1 个答案:

答案 0 :(得分:1)

在我看来,因为你使用

mRenderer.setAngleX(mRenderer.getAngleX() + (dx * TOUCH_SCALE_FACTOR));

即使dx为0,也会在下一次迭代中重新应用任何先前的角度(通过mRenderer.getAngleX())。 让dx单独修改mAngleX(当然,对mAngleY执行相同操作):

mRenderer.mAngleX += dx * TOUCH_SCALE_FACTOR;