Say i have something like this:
pos += glm::normalize(target - pos) //PLEASE NOTE: pos is a glm::vec3 and so is target
This makes "pos" translate towards "target", but what if i want to make my object to face "target"?
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It only takes a minute to sign up.
Sign up to join this communitySay i have something like this:
pos += glm::normalize(target - pos) //PLEASE NOTE: pos is a glm::vec3 and so is target
This makes "pos" translate towards "target", but what if i want to make my object to face "target"?
Making a model always face a point is trickier in 3d than it is in 2d: the added dimension makes one wonder "what about the UP?".
This here assumes that you want your model to stay vertical as much as possible, and it uses the following coordinate system.
// z+ y+
// | /
// | /
// | /
// | /
// |/
// ¯¯¯¯¯¯¯¯¯¯¯¯ x+
This also assumes that the 'front' vector of your model is in x+ and that the 'side' vector is y+ (and of course, 'up' is z+).
glm::vec3 dirglm( dir.x(), dir.y(), dir.z() ); // dir is normalized
// find the angle about world-frame-z-axis
double angle = std::atan2( dir.y(), dir.x() );
// Make the rotation matrix around the vertical (z) axis, adjusts the 'yaw'
glm::mat4 glmrotXY = glm::rotate( angle, glm::tvec3<double>( 0.0, 0.0, 1.0 ) );
// Find the angle with the xy with plane (0, 0, 1); the - there is because we want to
// 'compensate' for that angle (a 'counter-angle')
double angleZ = -std::asin( (dir).z() );
// Make the matrix for that, assuming that Y is your 'side' vector; makes the model 'pitch'
glm::mat4 glmrotZ = glm::rotate( angleZ, glm::tvec3<double>( 0.0, 1.0, 0.0 ) );
object->setRotationMatrix( glmrotXY * glmrotZ );
This will cause a behaviour similar to the one of a camera in a 3rd person view kind of game (I'm thinking MMORPG style). It has the caveat that you can't have 'pos' directly above or below.
You just need the standard lookat function.
#include <glm/gtc/matrix_transform.hpp>
glm::vec3 const up(0.f, 0.f, 1.f);
object->setRotationMatrix(glm::lookAt(pos, target, up));
That’s all! Replace (0.f, 0.f, 1.f) with whatever you want your “up” vector to be.
If direction and up vectors are collinear, then you're in trouble. I think direction by itself is not enough to describe orientation in 3D space. So the answer is no, you can't just convert direction into rotation matrix.