rshah
rshah

Reputation: 691

Rotating object around another object

So I have a camera object in my scenegraph which I want to rotate around another object and still look at it.

So far the code I've tried to translate its position just keeps moving it back and forth to the right and back a small amount.

Here is the code I've tried using in my game update loop:

//ang is set to 75.0f
camera.position += camera.right * glm::vec3(cos(ang * deltaTime), 1.0f, 1.0f);

I'm not really sure where I'm going wrong. I've looked at other code to rotate around the object and they use cos and sine but since im only translating along the x axis I thought I would only need this.

Upvotes: 1

Views: 641

Answers (1)

Rabbid76
Rabbid76

Reputation: 210877

First you have to create a rotated vector. This can be done by glm::rotateZ. Note, since glm version 0.9.6 the angle has to be set in radians.

float ang            = ....; // angle per second in radians 
float timeSinceStart = ....; // seconds since the start of the animation
float dist           = ....; // distance from the camera to the target

glm::vec3 cameraVec = glm::rotateZ(glm::vec3(dist, 0.0f, 0.0f), ang * timeSinceStart);

Furthermore, you must know the point around which the camera should turn. Probably the position of the objet:

glm::vec3 objectPosition = .....; // position of the object where the camera looks to

The new position of the camera is the position of the object, displaced by the rotation vector:

camera.position = objectPosition + cameraVec;

The target of the camera has to be the object position, because the camera should look to the object:

camera.front = glm::normalize(objectPosition - camera.position);

The up vector of the camera should be the z-axis (rotation axis):

camera.up = glm::vec3(0.0f, 0.0f, 1.0f);

Upvotes: 1

Related Questions