1
\$\begingroup\$

I'm developing some game in order to learn OpenGL.

I can make an object follow me around when I move forward, backward, left, right, up or down, by setting it's position right infront of the camera.

Problem starts when the camera rotates / tilts (looking up, down, left, right...).

The object is indeed sticks infront of the camera position (because I calculate a vector going out from the camera position and place it there), however I can't make the angle of the object to rotate/tilt along with the camera, so it is just fixed.

I think I might have to set the object coordinate system to correlate with the camera's coordinate system, but I can't figure out how. Maybe I'm wrong and there's another way to do that.

My game implementation

I have 4 vectors for the camera and 4 vectors for each object: origin, x, y and z (to represent the objects coordinate system).

To move the camera, I substract z axis from origin.

Same for other directions.

In order to tilt the camera, for example to the right, I just calculate rotation around Z axis and apply to X,Y axes.

Note: Movement in the world works good, in all directions and angles.

Here's the (the relevant) code I use to position objects in the world. Before drawing them I first put them in their origin (recall: I save an origin and x,y,z axes to all my objects), then do some scale to fit my desired size:

// translate to position
gl.glTranslatef((float)origin.x, (float)origin.y, (float)origin.z);
// scale to size
gl.glScalef((float)size.x, (float)size.y, (float)size.z);

Any ideas?

\$\endgroup\$
1
\$\begingroup\$

Your code should be placing the object in one fixed spot with no rotation. It sounds like you want it to be moving so that it's always viewed from the same angle by the camera whenever the camera moves. I guess these are basically like powerups then? If so I guess this makes sense to do.

The good news is that it is simple to rotate the object in the same way as the camera.

model = glm::translate(model, glm::vec3(position.x, position.y, position.z));
model = glm::scale(model, glm::vec3(scale));
model = glm::rotate(model, rotationAngle, glm::vec3(rotationAxis.x, rotationAxis.y, rotationAxis.z));

To find your rotation angle can be a little difficult though.

So You may find it easier to call the LookAt method for a perpendicular point.

You can find this with the cross product of the origin and the camera's up vector. The result is a vector that shoots off at a right angle from the view. Then you just have the object 'look at' this point.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.