# rotate around selected object

I use the mouse to select an object which the camera then looks at.
I use gluLookAt( cameraX, cameraY, cameraZ, targetX, targetY, targetZ, upX, upY, upZ )
where upX = 0 upY = 0 upZ = 1

That works fine.
Now I want to rotate the camera around the selected object. The selected object is in the middle of my view & the camera is looking at it. Whenever I rotate the camera, I want it to always be looking at the selected object in the middle of the view.

The problem is the camera rotates around but the selected object is no longer in the middle of the view. The camera seems to always look at the middle of the view 0,0,0 rather than at the object.
To do that I translate the camera & target to the origin, increase my horizontal angle, get the new look vector & translate back.
Here’s the code which does it:

``````cameraX -= targetX;
cameraY -= targetY;
cameraZ -= targetZ;

// target point is 0,0,0
lookVector = 0 - cameraX;
lookVector = 0 - cameraY;
lookVector = 0 - cameraZ;

double length = sqrt((lookVector * lookVector) + (lookVector * lookVector) + (lookVector * lookVector));

double horzAngle = (atan2(lookVector, lookVector));

double vertAngle = (acos(lookVector / length));

horzAngle += panSpeed*(pi/180);
if (horzAngle &gt;= (2*pi))
horzAngle -= (2*pi);

double newVector;
newVector = length * sin(vertAngle) * cos(horzAngle);
newVector = length * sin(vertAngle) * sin(horzAngle);
newVector = length * cos(vertAngle);

// target point is 0,0,0
cameraX = 0 - newVector;
cameraY = 0 - newVector;
cameraZ = 0 - newVector;

cameraX += targetX;
cameraY += targetY;
cameraZ += targetZ;
``````

Any ideas how to rotate & always look at what’s selected?

You said the problem was that the camera does not look at the target when you move it, but you didn’t supply any code showing how you orient the camera to point towards the object.

If you set the centerx, centery, and centerz in gluLookAt to the location of the object, it shouldn’t matter where the camera is.

Thanks.
I figured it out though.
Whenever I select an object, I slowly pan the camera over to the new object & I was calculating the difference between the angles of the current look vector & the new look vector & then slowly incrementing the angles until I got to the new position but I forgot to find the difference of the lengths of the look vectors & slowly increment the distance so it works fine now.