This problem has been troubling me for quite some time now and I can not seem to figure out the answer. I have a vector which I would like to align a 3d object along, in this case a ofxCone.
The cone should point along the white line towards the red sphere, which is slightly ahead in z space. However, I can not seem to figure out the math behind this to apply the transformations via glrotatef in one call or glrotatef for x, then y and then z.
How it should look:
ofxLightsOn();
ofxVec3f up(0, 1, 0);
ofxVec3f right(1, 0, 0);
ofxVec3f forward(0, 0, 1);
ofxVec3f center(0, 0, 0);
ofxVec3f tar(mouseX- ofGetWidth()*.5, mouseY- ofGetHeight()*.5, 200);
//ofxVec3f tar(100, 100, 100);
ofxVec3f normal = tar - center;
float rotx = normal.angle( forward );
float roty = normal.angle(right);
float rotz = normal.angle(up);
glPushMatrix();
glTranslatef(ofGetWidth()*.5, ofGetHeight()*.5, 0);
ofSetColor(255, 0, 0);
ofxSphere(tar.x, tar.y, tar.z, 50);
ofSetColor(150, 150, 150);
glPushMatrix();
glRotatef(rotx, 1, 0, 0);
glRotatef(roty, 0, 1, 0);
glRotatef(rotz, 0, 0, 1);
ofxCone(center, ofxVec3f(50, 180, 50), ofxVec3f(0, 0, 0) );
glPopMatrix();
ofxLightsOff();
ofSetColor(255, 255, 255);
drawLine(center, tar);
glPopMatrix();
You can download the project out here:
http://nickhardeman.com/labs/Axis-Align.zip