ZeunO8
ZeunO8

Reputation: 450

Is there a function to calculate this unit vector in glm?

I have the following function in c++ to calculate a unit vector:

glm::vec3 unit_vector(glm::vec3 v) {
    return v / (float)v.length();
}

Is there a glm equivalent I can use?

Upvotes: 0

Views: 2223

Answers (1)

Indiana Kernick
Indiana Kernick

Reputation: 5331

Well, v.length() actually returns the number of components of the vector (in this case: 3) so this function doesn't do what you think it does. There is a glm function that changes the magnitude of a vector to 1 (making it a unit vector). This operation is called normalizing. glm::normalize can do that.

Your function could be implemented like this:

#include <glm/geometry.hpp>

glm::vec3 unit_vector(glm::vec3 v) {
    return glm::normalize(v);
}

Or just use glm::normalize directly.

Upvotes: 2

Related Questions