Re: Translating a rotated model.
Posted by ericg on Oct 09, 2014; 3:08am
URL: https://forum.jogamp.org/Translating-a-rotated-model-tp4033250p4033290.html
Just to close out this thread I have the solution. First I have to say that using Quaternions for rotation is a no brainer - the jogamp Quaternion class is perfect as the rotations seemed to be much smoother than using my own rotation calculations. Also used the FloatUtils for creating a lookAt matrix.
The core of my problem was that I was focusing on transforming only one axis at a time. I needed to transform both x and z simultaneously.
//draw a field of planes adjacent to Y
for ( x = -10 ;x < 10 ; x+=2){
for ( z = -10 ; z < 10 ; z+=2){
//init matrices (thanks FloatUtil!!)
FloatUtil.makeIdentity(view2);
FloatUtil.makeIdentity(vw2);
//set eye, centre and Up (these can be modified via keyboard input etc..)
float[] eye = {0, 10, -30};
float[] center = {0,0,0};
float[] up = {0,1,0};
float[] mat4Tmp = new float[16];
//create lookAt matrix (FloatUtil, what would I do without you?)
FloatUtil.makeLookAt(view2, 0, eye, 0, center, 0, up, 0, mat4Tmp);
//rotate the scene using quaternion. rotangle always +tive 0-360.
q = q.setIdentity();
q = q.rotateByAngleNormalAxis( (float) Math.toRadians(rotAngle), 0, 1, 0);
q = q.normalize();
//load mx to float array
q.toMatrix(vw2, 0);
//mult rotation and perspective (can be done in shader, here for testing purposes)
view2 = multiply( view2, vw2);
//apply the updated translation co-ords to vertices
view2 = translate(view2, (float)-transX-x, transY, -(transZ-z));
gl.glUniformMatrix4fv(iModelView, 1, false, view2, 0);
//link projection matrix to 'mat4 projection' on vertex shader.
gl.glUniformMatrix4fv(iProjection, 1, false, projection, 0);
gl.glDrawArrays(GL3.GL_TRIANGLES, 0, 6); //draw 2 triangles (6 vertices).
}
}
//The values for transX, transY and transZ make it all come together.
public void keyPressed(KeyEvent arg0) {
//get camera angle on y axis.
double convA = Math.toRadians( -rotAngle + 90);
switch (arg0.getKeyCode()){
case KeyEvent.VK_D:
transZ += Math.sin( convA - Math.PI / 2 );
transX -= Math.cos( convA - Math.PI / 2 );
break;
case KeyEvent.VK_A:
transZ -= Math.sin( convA - Math.PI / 2 );
transX += Math.cos( convA - Math.PI / 2 );
break;
case KeyEvent.VK_W:
transZ += Math.sin( convA );
transX -= Math.cos( convA );
break;
case KeyEvent.VK_S:
transZ -= Math.sin( convA );
transX += Math.cos( convA );
break;
case KeyEvent.VK_Z:
rotAngle -= (4);
if (rotAngle < 0){
rotAngle += 360;
}
break;
case KeyEvent.VK_X:
rotAngle += (4);
break;
default:
break;
}
rotAngle %= 360; //mod 360
}
Works like a charm! Two weeks later...