PDA

View Full Version : How to set model view matrix in iOS OpenGL ES?



useruser
12-03-2014, 11:55 PM
I'm new to OpenGL and have no idea to set values to model matrix or view matrix. Sorry if I ask something so basic. As far as I know, model view matrix is composed of model matrix(object position) and view matrix(camera position). I'm trying to change the camera position but I don't know how to do so. I wrote some code as below.

in viewDidLoad


viewMatrix = GLKMatrix4Make(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); // identity matrix
modelMatrix = GLKMatrix4Translate(GLKMatrix4Identity, 640/2, 1136/2, 0);
modelviewMatrix = GLKMatrix4Multiply(modelMatrix, viewMatrix);
self.baseEffect.transform.modelviewMatrix = modelviewMatrix;

and when the screen is swiped up, I want to rotate only the camera


-(void)rotateUp:(UISwipeGestureRecognizer *)gestureRecognizer
{
viewMatrix = GLKMatrix4Rotate(modelviewMatrix, 0.1f, 1.0f, 0.0f, 0.0f); // rotation around X-axis
modelviewMatrix = GLKMatrix4Multiply(modelMatrix, viewMatrix);
self.baseEffect.transform.modelviewMatrix = modelviewMatrix;
}

but this does not work. Can anyone tell me how to fix this and how to set the initial model matrix and view matrix?

GClements
12-04-2014, 07:46 AM
The model-view matrix should transform the object coordinates (the values in the vertex array corresponding to position) to eye coordinates (where the viewpoint is at the origin and the view direction along the negative Z axis).

A moveable camera is implemented by pre-multiplying any object transformation with the inverse of the camera transformation.

I'm not familiar with the Apple APIs, but I suspect that you want


modelviewMatrix = GLKMatrix4Multiply(GLKMatrix4Invert(viewMatrix), modelMatrix);


Also, for an object to be in front of the camera, its camera-space Z coordinate needs to be negative. Assuming that the camera hasn't been rotated, if the camera is at the origin, the object's Z coordinate should be negative; if the object is at the origin, the camera's Z coordinate should be positive.

useruser
12-04-2014, 09:26 PM
Thank you so much. I changed the two lines of multiplication into
modelviewMatrix = GLKMatrix4Multiply(GLKMatrix4Invert(viewMatrix, nil), modelMatrix); but after swiping the screening up all my objects still disappeared. I wonder if I set the viewmatrix's initial value correctly. I just set it indentity matrix.
I still have no idea why just pre-multiplying an invert can change the camera perspective not the object perspective.